Entity Framework Code First

Code First development with Entity Framework

New approaches to modeling for Entity Framework 4.1.

  1. Code First
  2. Model First
  3. Database first

Let's go through Code First implementation in this blog.



In Code First approach, you avoid working with visual model designer (EDMX) completely. You write your POCO classes first and then create database from these POCO classes. Developers who follow the path of Domain-Driven Design (DDD) principles prefer to begin by coding their classes first and then generating the database required to persist their data.  

In addition to supporting a designer-based development workflow, EF4 also enables a more code-centric option which we call “code first development”.  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

EF’s “code first development” support is currently enabled with a separate download that runs on top of the core EF built-into .NET 4

So as a developer, you first start writing C#/VB.net classes rather than focusing on database design and then when you run the application, Code First APIs will create the new database or map your classes with existing database before running your application.

Modeling with Entity Framework Before Code First

The first iteration of Entity Framework, which came as part of .NET 3.5 and Visual Studio 2008, gave developers the ability to create this conceptual model by reverse engineering an existing database into an XML file. This XML file used the EDMX ex-tension, and you could use a designer to view and customize the model to better suit your domain. Visual Studio 2010 and .NET 4 brought the second version of Entity Framework, named Entity Framework 4 (EF4), to align with the .NET version. On the modeling side, a new capability called Model First was added. Here you could design your conceptual model in the visual designer and then create the database based on the model.

Model First allows developers working on new projects that do not have legacy data-bases to benefit from the Entity Framework as well. Developers can start with a focus on their application domain by designing the conceptual model and let the database creation flow from that process. Whether designing the EDMX by the database-first or model-first way, the next step for creating your domain is to let automatic code generation build classes based on the entities and their relationships that it finds in the model. From here, developers have strongly typed classes representing their domain objects—whether those are custom- eras, baseball cards, or fairy-tale characters—and can go on their merry way developing their software  applications around these classes.

Another critical change came in EF4. In .NET 3.5, The only way Entity Framework was able to manage in-memory objects was by requiring classes to inherit from Entity Framework’s Entity Object. The Entity Object communicates its changes to Entity Framework, which in turns keeps track of changes and eventually is able to persist them back to the database. In addition to this functionality, .NET 4 introduced POCO (Plain Old CLR Object) support to enable the Entity Framework to track changes to simpler classes without needing the Entity Object to be involved. This freed up developers to use their own classes, independent of Entity Framework. The EF runtime had a way of being aware of the classes and keeping track of them while in memory.

Inception of Code First

Code First lets you define your domain model with code rather than using an XML-based EDMX file. Even though Model First and Database First use code generation to provide classes for you to work with, many developers simply did not want to work with a designer nor have their classes generated for them. They just wanted to write code.

In Code First you begin by defining your domain model using POCO classes, which have no dependency on Entity Framework. Code First can infer a lot of information about your model purely from the shape of your classes. You can also provide additional configuration to further describe your model or override what Code First inferred. This configuration is also defined in code: no XML files or designers.

Code First - Work flow

Let’s create first simple code first example

Create the Class Library project in Visual Studio 2010. Write two simple Student and Standard entity classes as below (You can use Entity Framework 4.1/4.3/5.0 for this example.): 

Student Class:  

    public class Student


        public Student()



        public int StudentID { get; set; }

        public string StudentName { get; set; }


Standard Class:  

    public class Standard


        public Standard()



        public int StandardId { get; set; }

        public string StandardName { get; set; }

        public string Description { get; set; }


Now, create context class which is derived from DBContext class with two DbSet properties, one for Student and one for Standard. 

    namespace SchoolDataLayer


        public class Context: DbContext


                public Context(): base()



                public DbSet Students { get; set; }

                public DbSet Standards { get; set; }



Now, create console project to test these classes as below:   

    using (var ctx = new Context())


        Student stud = new Student() { StudentName = "New Student" };





Beauty of Code First APIs of Entity Framework: It creates the database based on parameter passed in the base constructor of your context class. We have not passed any parameters so it will create “SchoolDataLayer.Context” database in local SQLEXPRESS. 

Code-first API will also create two tables in the database, Students and Standards table based on Student and Standard class. Code First APIs creates PrimaryKey in the table if class has either “Id” or ClassName + “Id” property. For example, Student class has “StudentId” property so it will create StudentId as PK column. It will also create other columns with the same name and datatype as property names and datatype as below.

Code first -tables creation

So this way without creating database first, you can start writing application that will eventually create the database from your domain classes.

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.

Configure Domain Classes in Code-First:

As you know that you can create entity data model from existing database in database first approach that has all the metadata information in SSDL, CSDL and MSL so that EF can use this model in querying, change tracking, updating functionality etc.. The same way, entity framework code first allows you to use your domain classes to build the model which in-tern will be used by EF in different activity. Code first suggests certain conventions to follow by your domain classes so that EF can understand it and build the model out of it.

However, if your domain classes don’t follow conventions then you also have the ability to configure your domain classes so that EF can understand it and build the model out of it. There are two ways by which you can configure your domain classes:

  1. DataAnnotation
  2. Fluent API



DataAnnotation is simple attribute based configuration which you can apply on your domain classes and its properties. 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. 

Following is an example of DataAnnotation used in Student Class:    


    public class Student


        public Student() { }      


        public int SID { get; set; }

        [Column("Name", TypeName="ntext")]


        public string StudentName { get; set; }


        public int? Age { get; set; }     

        public int StdId { get; set; }


        public virtual Standard Standard { get; set; }



Fluent API:

Fluent API configuration applied as EF building the model from your domain classes. You can inject the configurations by overriding the DbContext class’s OnModelCreating method as following:   

    public class SchoolDBContext: DbContext


        public SchoolDBContext(): base("SchoolDBConnectionString")



        public DbSet Students { get; set; }

        public DbSet Standards { get; set; }

        public DbSet StudentAddress { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)


            //Configure domain classes using Fluent API here




Use model Builder which is an object of DbModelBuilder class to configure domain classes.

Using code-first approach can configure the following type of relationships

  • One-to-One
  • One-to-Many
  • Many-to-Many

Migration in Code-First:

Entity framework code first has 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 (other than seed data) or existing Stored Procedures, triggers etc in your database then these strategies used to drop the entire database and recreate it and so you lose the data and other db objects.  

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

There is two kind of Migration:

  1. Automated Migration
  2. Code based Migration









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 CodeFirst Approach

Entity Framework Code First Approach Entity Framework is an enhancement to an existing ADO.Net ...

Read More >


Post a Comment

  • Recent
  • Popular
  • Tag
Monthly Archive

Contact Us
  • *
  • *