Entity Framework Code First Approach

We will create plain .NET classes as model classes for MVC and get ORM and the entity frame work functionality using the context classes. Once we create model and the context classes, we can directly start building our app with the required controllers and views when compared with other models of the entity frame work. We do not use any ORM designer to build the classes.

From Entity Framework 5.0, the database first approach also generates code first style of classes but with the designer and other mapping related files, the code first is the most light weight approach of building MVC based Websites (with many entities also).

Now open VS. Create a New Project ,say CodeFirstDemo. Choose ASP.NET Web Application. Select MVC Template and click OK.

ASP.NET web application

Now, create a new class, say, Shop.cs, under the Model Folder and write the code under Shop.cs.

Add Required properties under Shop.cs. By default “Id” or “ShopID” is treated as primary key column in the database once the database is created. Other than these names, you should add “[key]” attribute on top of the property. 

Add class

Shop.cs

Now, create another class, say, Customer.cs, under the Model Folder and write the code under Customer.cs.

Customer.cs

Now, add Context Class, say, EXPShopContext.cs under the Model Folder and write the code under EXPShopContext.cs but first, you should add Namespace, using System.Data.Entity.

EXPShopContext

Build the project and add the controller.

Build the Project

Add Controller

Check generate views. Click add controller with all CRUD operations, the views are generated in Solution Explorer. Check in the controllers and the views.

Controllers and Views

Run the Application.

Run the Application

Click create new link and add the field or add some record.

create New Link

Index

Check all the operation’s (Create New, Edit, Details and Delete).

Where is the data stored?

  1. By default, EFW code first creates SQL SERVER Express DB in “App_Data” folder of project. 
    If you want to target your own database with all our parameters and location,  then go to web.config and create a connection string with the name as our context class name (Context class name and connection string name should be the same).

Example

  1. <add name="MyContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\emp.mdf;Initial Catalog=emp;Integrated Security=True" providerName="System.Data.SqlClient" />  
In this, emp.mdf is our database name (here database name and initial catalog name should be the same).

 

Up Next
    Ebook Download
    View all
    Learn
    View all