Entity Framework Code First

Entity Framework introduced Code First approach from Entity Framework 4.1. This tutorial covers all the features of Entity Framework Code-First. We will start with the basics of code-first and then we will see how we can configure one-to-one, one-to-many and many-to-many relationship with DataAnnotation as well as Fluent API. We will also see migration which was introduced in EF 4.3. We will use Entity Framework 4.1 and 4.3/5.0 in this tutorial.

What is Code-First?

Entity Framework introduced Code First approach from Entity Framework 4.1. Code First is mainly useful in Domain Driven Design In the Code First approach, you can focus on the domain design and start creating classes as per your domain requirement rather than design your database first and then create the classes which matches your database design. Code First APIs will create the database on the fly based on your entity classes and configuration. 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. So the basic workflow would be: Write code-first application classes → Hit F5 to run the application → Code First API creates new database or map with existing database from application classes → Inserts default/test data into the database → Finally launch the application

Simple Code First Example

Let’s create a simple code first example. Create a Class Library project in Visual Studio. Write two simple Movie and Actor entity classes as below:

Actor class:

public class Actor
{
    public Actor()
    { 
    }
    public int ID { get; set; }
    public string FullName { get; set; }
}

Movie class:

public class Movie
{
    public Movie()
    { 
    }
    public int ID { get; set; }
    public string Title { get; set; }
}

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

namespace MovieDataLayer
    {
        
        public class Context: DbContext 
            {
                public Context(): base()
                {
            
                }
                public DbSet<Actor> Actors { get; set; }
                public DbSet<Movie> Movies { get; set; }
            }
    }

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

using (var ctx = new Context())
    {
        Actor actor = new Actor() { FullName = "Will Smith" };
        ctx.Actors.Add(actor);
        ctx.SaveChanges();                
    }

Now, if you run the application then you will surprise to see that application run successfully.

It has successfully stored Actor information into the database. But where is the database and what are the tables and its columns?

This is the 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 pass any parameters so it will create “ActorDataLayer.Context” database in local SQLEXPRESS

Code-first API will also create two tables in the database, Actors and Movies table based on Actor and Movie class. Code First API creates PrimaryKey in the table if class has either “Id” or ClassName + “Id” property. For example, Actor class has “ID” property so it will create ID as PK column. It will also create other columns with the same name and datatype as property names and datatypes.

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

Database Initialization

Let’s how database initialize in code-first application.

No Parameter: If you do not pass the parameter then it creates the database in your local SQLEXPRESS with name matches your {Namespace}.{Context class name}. eg. MovieDataLayer.Context for following context:

 public class Context: DbContext 
{
    public Context(): base()
    {
    }
}

Name: If you pass “Name” parameter then it creates database in the local SQLEXPRESS db server using that name. For example: below code will create “ActorDB-CodeFirst” database

 
public class Context: DbContext 
{
    public Context(): base("MovieDB-CodeFirst") 
    {
    }
}

ConnectionStringName: If you pass connection string name of app.config or web.config then it will create the database as per connection string. For example, below code will create “ActorDB-ByConnectionString” database:

 
 public class Context: DbContext 
{
    public ActorDBContext() : base("ActorDBConnectionString") 
    {
    }
}

App.config:

 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="MovieDBConnectionString" 
    connectionString="Data Source=.;Initial Catalog=ActorDB-ByConnectionString;Integrated Security=true" 
    providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

Above Context class sends connection string name as a parameter. So it will create new “MovieDB-ByConnectionString” database or use existing “MovieDB-ByConnectionString” database at local SQL Server (because we have mentioned ‘.’ not SQLEXPRESS). Make sure that you include providerName = “System.Data.SqlClient” in the connection string.

Be first to comment

Leave a Reply