Introduction To Entity Framework Code First

Here, I am starting a series on Entity Framework (EF). In this article we focused on CODE FIRST approach but before tha we must first understand Entity Framework itself and different approaches available.

Entity Framework

EF is a tool to fetch and send to database and it's one kind of Object Relational Mapper (ORM). With EF you can work with relational databases.

Drastically reduce the manual code writing in the projects. It's very easy and simple to receive and send the data to database.

Object Relation Mapping (ORM) which take care of creation and updation of classes, database and its tables.

Its an open source project and you can also contribute your efforts in this, following is link:

Basically Entity Framework having following three approaches:

  1. Code First: On the basis of Class (POCO) your database will be created.

    POCO : Plain Old CLR Object

  2. Model First: On the basis of Entity Framework Designer to design the relation and entities then your Database is generated.

  3. Database First: On the basis of your Database Model and relation will be created.

Code First

  1. With code first your class(POCO) models become our database. We know the structures and designs and what generates the database. There are no additional files and there is no need to create a class extension when we want to add properties or whatever else that the database doesn't need to know about. We can just add them into the same class as long as you follow the proper syntax.

  2. When we go for Database first approach, we’re fully depended on what gets generated for our models for uses in our application. Occasionally the naming convention is undesirable and not as we want, sometimes the relationships and associations aren't quite what we want. Code first is better than Database first.

  3. While choosing CODE First we can control every aspect of both our class(POCO) code models and our database design from the comfort of business object. We can precisely specify relationships, constraints, and associations. We can set property Maximum limits of data types and database columns sizes.

Herewith, we start with Code First approach with Asp.Net MVC.

Do the followings steps,

  1. Create a new ASP.NET MVC4 application and select Basic template.

  2. Give your project name as EntiryFrameworkCodeFirst.

  3. Add new Class file named Friend.Cs.

    Add class

    In FRIEND.CS file we are going to write our Class (POCO) definition.

    FRIEND.CS code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. namespace EntiryFrameworkCodeFirst  
    6. {  
    7.     public class Friend  
    8.     {  
    9.         public int Id  
    10.         {  
    11.             get;  
    12.             set;  
    13.         }  
    14.         public string FriendName  
    15.         {  
    16.             get;  
    17.             set;  
    18.         }  
    19.         public string Address  
    20.         {  
    21.             get;  
    22.             set;  
    23.         }  
    24.         public string City  
    25.         {  
    26.             get;  
    27.             set;  
    28.         }  
    29.         public string Phone  
    30.         {  
    31.             get;  
    32.             set;  
    33.         }  
    34.     }  
    35. }  
  4. Now add an another class file named FriendDBContext.cs,

    Class

    In FriendDBContext.cs file we are going to write DbSet property of Friend class with get and set.

    FriendDBContext.cs code,
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data.Entity;  
    4. using System.Linq;  
    5. using System.Web;  
    6. namespace EntiryFrameworkCodeFirst  
    7. {  
    8.     public class FriendDBContext: DbContext  
    9.     {  
    10.         public DbSet < Friend > Friends  
    11.         {  
    12.             get;  
    13.             set;  
    14.         }  
    15.     }  
    16. }  
    Why this class named FriendDBContext?

    Because while we run the application our Web.Config file search connection strings with this name only.
    1. <connectionStrings>  
    2.     <add name="FriendDBContext" connectionString="Data Source=SAIBABA-PC\SAIBABA;Initial Catalog=FriendDB;Integrated Security=True;" providerName="System.Data.SqlClient" />   
    3. </connectionStrings>  
    After reading above statement might be you think the about following questions:

  5. Global.Asax.cs file updation.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Http;  
    6. using System.Web.Mvc;  
    7. using System.Web.Optimization;  
    8. using System.Web.Routing;  
    9. namespace EntiryFrameworkCodeFirst  
    10. {  
    11.     // Note: For instructions on enabling IIS6 or IIS7 classic mode,   
    12.     // visit http://go.microsoft.com/?LinkId=9394801  
    13.     public class MvcApplication: System.Web.HttpApplication  
    14.     {  
    15.         protected void Application_Start()  
    16.         {  
    17.             AreaRegistration.RegisterAllAreas();  
    18.             WebApiConfig.Register(GlobalConfiguration.Configuration);  
    19.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
    20.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
    21.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
    22.             //Code First Initialize  
    23.             FriendDBContext _friendDBContext = new FriendDBContext();  
    24.             _friendDBContext.Database.Initialize(true);  
    25.         }  
    26.     }  
    27. }  
    This line very important,
    1. //Code First Initialize  
    2. FriendDBContext _friendDBContext = new FriendDBContext();  
    3. _friendDBContext.Database.Initialize(true);  
  6. Database List Before Running Application:

    Database List

  7. Before going for this step first build your solution first.

    Now add a new controller first by right click CONTROLLERS folder or by simply pressing Ctrl+M, Ctrl+C.

    add a new controller

    Solution Explorer before clicking Add button

    Solution Explorer

    After clicking on Add button . Visual studio creates the Following things:

      a. Controller
      b. Views file for -> Create, Index and Edit, Delete.

    Solution Explorer After clicking Add button,

    Controller

  8. Before pressing F5 or running application change RouteConfig.cs file.

    RouteConfig.cs file exists under directory App_Start.

    We had changed the Controller Name = Friend only, the  rest of things keep as they are.

    RouteConfig.cs code

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. using System.Web.Routing;  
    7. namespace EntiryFrameworkCodeFirst  
    8. {  
    9.     public class RouteConfig  
    10.     {  
    11.         public static void RegisterRoutes(RouteCollection routes)  
    12.         {  
    13.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
    14.             routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new  
    15.             {  
    16.                 controller = "Friend", action = "Index", id = UrlParameter.Optional  
    17.             });  
    18.         }  
    19.     }  
    20. }  
    Now Press F5 to run project.

    Check your FriendDB database will be created in your SQL Server.

    database

    Because of there is no data in Friends table that's why it appearing like this way.

    output

    You can Add/Insert a new data/record by click on Create New.

    Friends table

    Index

Read more articles on Entity Framework:

Up Next
    Ebook Download
    View all
    Learn
    View all