16Jun

Entity Framework CodeFirst Approach

Entity Framework Code First Approach

 

Entity Framework is an enhancement to an existing ADO.Net technique and ORM framework we used for Microsoft technologies.

The Entity framework is an object-relation mapper, means it takes the structure of the database and turns it into objects that the .Net framework can understand. Developers use those object to interact with the database instead of interacting with database directly. It’s possible to perform the full set of Create, Read, Update, and Delete (CRUD) operations.

There are the following 3 approaches we use during application development:

  1. Code First.

  2. Model First.

  3. Database First. 

Let’s go through Code first approach in this blog.

Introduction:

The Code first approach is introduced in Entity Framework 4.1, and is the latest workflow Microsoft has introduced.

Code first approach lets us transform our coded classes into database application, which means code first lets us to define our domain model using POCO (plain old CLR object) class rather than using an XML-based EDMX files which has no dependency with Entity Framework.

Our model classes becomes the domain models, therefore we most have to be very conscious in designing our model classes. And the rest of the work will be done by Entity Framework. This is the beauty of code first approach where our model classes are become the data models on which Entity framework relies.

 

   CodeFirst

 Code-First Development enables a pretty sweet development workflow.  It enables you to:

  • Develop without ever having to open a designer or define an XML mapping file

  • Define your model objects by simply writing “plain old classes” with no base classes required

  • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything

  • Optionally override the convention-based persistence and use a fluent code API to fully customize the persistence mapping

As a developer ,you first start by c# or VB.net classes and context class. when you run the appliaction ,Codefirst API's will create the new database(if it does not exists) and map your classes with the database using default Codefirst  conventions. you can also configure your domain classes to override default conventions to map with database tables using Data annotation attribute or fluent API.

Let us create simple Code first example with Asp.net MVC application.

1)    Create a class library Project in Visual studio. Create two simple Company and Employee model classes as shown below.

Company class:

public class Company

{

      public Company()

      {

      }

     public int CompanyID { get; set; }

     public string CNAME  { get; set; }

     public string ADDRESS { get; set; }

}

 

Employee class:

public class Employee

{

     public Employee()

     {

     }

    public int EmployeeID { get; set; }

    public int  CID { get; set; }

    public string ENAME { get; set; }

    public string PHONE { get; set; }

    public string EMAIL { get; set; }

}

 

1)    To MVC Project we need to install Entity framework from NuGet package manager, Select Project -> right click -> Manage NuGet Packages -> Search Entity Framework -> Install. Refer below screenshot.

 

nuget

 

Now Create Context class which is derived from DBContext class with two DBset Properties, one for Company and one for Employee.

 

CEContext class:

public class CEContext : DbContext

{

     public CEContext( )  :  base( " name=DBconnect "

     {

     }

     public DbSet<Company> Companies { get; set; }

     public DbSet<Employee> Employees { get; set; }

}

This simple class represents the whole data layer of our application. “DBconnect” string is the ConnectionString name defined in web.config file.

Dbcontext: This Class is responsible for interaction with database, and also to manage the entity objects during runtime, which includes populating objects with data from database, change tracking, persisting data to the database.

Dbset: This class represents an entity set that is used for the CRUD operations.

 

ConnectionString in web.config file is as shown below:

webConfig

Configuring the domain classes in code first approach:

Entity framework code first allows you to use your domain classes to build the model which in-turn will be used by EF in different activity. Code first suggests certain conventions to follow by your domain classes so that Entity framework can understand it and build model out of it.

There are two ways by which we can configure our domain classes:

1.DataAnnotation.                                                                                                             

2. Fluent API

 

DataAnnotation:

EF code first Provides a set of data annotation attributes, which we can apply to our domain classes and properties. DataAnnotation attributes override default code-first conventions.

You can find most of the attributes in System.ComponentModel.DataAnnotations namespace. However DataAnnotation provides only subset of Fluent API Configurations. So if you don’t find some attributes in DataAnnotation then you have to use Fluent API to configure it.

Below is the example of DataAnnotation used in Employee Class:

[ Table("Employee")]

public class Employee

{

      [Key]

      [Column("EmployeeID", TypeName = "int")]

      public int EmployeeID { get; set; }

      [Column("CID", TypeName = "int")]

      public int CID { get; set; }

      [MaxLength(50)]

      [Column("ENAME", TypeName = "nvarchar")]

      public string ENAME { get; set; }

      [MaxLength(10)]

      [Column("PHONE", TypeName = "nvarchar")]

      public string PHONE { get; set; }

      [MaxLength(50)]

      [Column("EMAIL", TypeName = "nvarchar")]

      public string EMAIL { get; set; }

      [ForeignKey("CompanyID")]

      public virtual Company Company { get; set; }

}

Fluent API:

Fluent API is another way to configure your domain classes. Fluent API provides more functionality for configuration than DataAnnotation. You can insert the configuration by overriding the Dbcontext class’s OnModelCreating method as follows:

public class CEContext : DbContext

{

     public CEContext() : base( " name=DBconnect "

     {

     }

     public DbSet<Company> Companies { get; set; }

     public DbSet<Employee> Employees { get; set; }

     protected override void OnModelCreating(DbModelBuilder  ModelBuilder)

     {

             //Configure Domain classes using fluent API here.

             base.OnModelCreating(ModelBuilder);

      }

}

Now in Index ActionResult within the Home controller write the following code to add data to Company table.

using( var Context = new CEContext() )

{

      try

      {

             Company ObjCompany = new Company() { CNAME = "Canarys" };

             Context.Add( ObjCompany );

             Context.SaveChanges();

       }

      catch( Exception E )

      {

            throw E;

       }

}

After the Execution of the above code, two Tables Company and Employee are created in the database as shown below.

 

 dbsnapshot

 

Migrations in Code First:

Entity Framework Code-first had different database initialization strategies prior to EF 4.3 like CreateDatabaseIfNotExists, DropCreateDatabaseIfModelChanges, or DropCreateDatabaseAlways. 

However, there were some problems with these strategies, for example if you already have data or existing stored procedures, triggers etc in your database , these strategies used to drop the entire database and recreate it, so you would lose the data and other data objects.

Entity framework 4.3 has introduced a migration tool that automatically updates the database schema, when your model changes without losing any existing data or other database objects. It uses a new database initializer called MigrateDatabaseToLatestVersion.

There are two kinds of migration:

  1. Automated Migration

  2. Code based Migration

 

Inheritance Strategy in Code-First:

In the code first approach, database schema will be created based on the design of your domain classes. You may design your domain classes in object-oriented way where you can use inheritance and polymorphism. Object-oriented systems model has “has a” and “is a” relationships where as SQL based relational model has only “has a” relationships. So how would you map object-oriented with relational database?  

There are three different approaches to represent an inheritance hierarchy:  

  • Table per Hierarchy (TPH): This approach suggests one table for entire class inheritance hierarchy. Table includes discriminator column which distinguish between inheritance classes.
  • Table per Type (TPT): This approach suggests one table for each classes thus each class will have its persistence table.
  • Table per Concrete class (TPC): This approach suggests one table for one concrete class but not for abstract class. So if you inherit abstract class in multiple concrete classes then properties of abstract class will be part of each table of concrete class.

Using Code-first approach we can configure the following type of relationships.

1. One to one

2. One to many

3. Many to many

 

References:

http://www.entityframeworktutorial.net/code-first/entity-framework-code-first.aspx
 
https://msdn.microsoft.com/en-us/data/jj200620.aspx
 

 

Related

ASP.NET: Audit Trail Implementation using Entity Framework

When you are working with certain projects which involves the Customer records, you might need to tr...

Read More >

Entity Framework Code First

Code First development with Entity Framework New approaches to modeling for Entity Framework 4.1. Co...

Read More >

Share

Post a Comment

  • Recent
  • Popular
  • Tag
Monthly Archive
Subscribe
Name

Contact Us
  • *
  • *