Code First Demo

By | October 29, 2018
  • Open Visual Studio. Create a new Console Application project and named it to CodeFirstDemo
  • Install Entity Framework by using NuGet Package Manager Console
PM> Install-Package EntityFramework
  • With code first we start with the code. So we will not going to Management Studio and create a new database. Instead we will create a new class called Post with following definition-
public class Post
{
    public int Id { get; set; }
    public DateTime DatePublished { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}
  •  Now we will need to create a DbContext class. So create a class called BlogDbContext as follows-
public class BlogDbContext:DbContext
{
    public BlogDbContext()
        :base("connectionstring")
    {
    }
    public DbSet Posts { get; set; }
}

Note: DbContext is an abstraction over the database that we use to load or save data.

In a particular DbContext class basically what we do-

Derive the class by DbContext.

Specify the Connection String to the database.

Expose one or more DbSet(s).

So what we did here-

We created a class that derived from DbContext. Also we exposed a DbSet of type Post class and named it to Posts.

  • Now we will define the connection string inside app.config as follows-

<add name=”BlogDbContext” connectionString=”data source=(local); initial catalog=CodeFirstDemo; user id= sa; password=***;” providerName=”System.Data.SqlClient”/>

Here we give the connection string name same as DbContext class name i.e. BlogDbContext

Then we set our connectionString where-

We set

(a). data source = (local)

It means we use local database server

(b). Initial catalog = CodeFirstDemo

It means our database name = CodeFirstDemo i.e. initial catalog means database name

(c). user id = sa

(d). password = ***

When we use user id and password in connection string it means we are using Sql Server authentication.

One more element we need to add in our connection string which is

(e). providerName = “System.Data.SqlClient”

Here we defined the provider name to System.Data.SqlClient. This is required to work with code first.

  • Now we need to enable code first migration. So go to Package Manager Console and write following command-
PM> enable-migrations

This is the command that we run only once for the lifetime of the project

So Code First Migrations enabled for the CodeFirstDemo project-

So created a folder inside project called Migrations as follows-

Among above steps there have some steps like “installing entity framework”, “adding the connection string” and “enabling migrations” are the steps that we do only once for the project lifetime.

Every time we want to make any change our model we start with the code. So in this case we will change inside our Post class.

  • Every time we make any change to our model or create any new model, we need to create a migration. Though we created Post class for the very first time so we have to create/add a migration. So go to Package Manager Console and run following command-
PM> add-migration CreatePost

Here add-migration is the command for adding migration.

In add migration also needs to specify the name of the migration that represents the content change we have made. In this example we created the Post class. So the name of our migration is CreatePost.

So migration CreatePost added.

Let’s see what happened due to adding migration-

Go to Solution Explorer-> Migrations folder.

Inside Migrations folder we have two files-

First one is our migration file. Here file name is with datetimestamp+MigrationName. This is very similar to what we had created in DatabaseFirstDemo by creating ChangeScript. But it is more automated fashion. Let’s see what inside the class-

namespace CodeFirstDemo.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class CreatePost : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Posts",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        DatePublished = c.DateTime(nullable: false),
                        Title = c.String(),
                        Body = c.String(),
                    })
                .PrimaryKey(t => t.Id);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.Posts");
        }
    }
}


We don’t have any SQL code here. This is plain C# code. The class CreatePost derives from DbMigration. It has two methods- Up() and Down(). Up() method use to upgrade database. Down() method uses to downgrade database.

With code first migrations we can take any database and take it to any version whether that version is higher or lower. This is very powerful. It we maintain different versions of any application this is going to be our best friend.

Now let’s see what happening inside the Up() method.

There is a call to this metho CreateTable. It tries to create a Table called dbo.Posts with following columns-

Id: it’s type is int. it is not nullable and it’s an identity column

DatePublished: It’s type is datetime and it is not nullable

Title: its type is string

Body: its type is string

Finally call to PrimaryKey method which specify that the Id column should be primary key.

  • So to run the migration we go back to package manager console and run following command-
PM> update-database

update-database command runs as follows-

Entity Framework uses convention over configuration. So when it looks at our model in this case Post class based on the name and type of our properties it can figure out how the database should looks like. For example it knows about the Id is typically used for primary key and often it’s an identity column. So it automatically added all expression inside CreateTable method and PrimaryKey method.

So we created a Code first migration. The next step is to run it. When we run it entity framework looks at the database, it takes the current version and figure out what migrations should run on the database to bring it up to date. Then it get the migration class and converts them to sql code and runs it on the database.

In this example it realize that …_CreatePost is the only migration that needs to be run on the database and it run the migration. So let’s see the result-

Go to management studio. There created a database called CodeFirstDemo as follows-

In this case we didn’t created the database from management studio. We just focused on the code.

We have two tables inside the database. One is _MigrationHistory is used internally by entity framework to figure out what migrations have been run on this database. Second one is Posts table that has following columns-

23 Total Views 1 Views Today
Md. Mojammel Haque

CSM, CSPO, CSD, CSP-SM, CSP-PO (ScrumAlliance.org)
Certification Profile Link-
https://www.scrumalliance.org/community/profile/mhaque13

Currently working as Lead Team (Application Architecture) at Raven Systems Ltd. Passion for software development especially agile practices such as TDD with in depth knowledge of Object Oriented Programming, SOLID Principles, Gang of Four Design Patterns, Some Enterprise Application Architectural Patterns. Over 8 years of software development experience ASP.NET. Has the ability to understand and transform complex business requirements into software ensuring applications are delivered on time. Also experience in non Microsoft .NET technologies such as Dapper.Net, Git, Structure Map & Angular, Bootstrap, HTML-5, CSS-3 etc.

Category: Entity Framework
Md. Mojammel Haque

About Md. Mojammel Haque

CSM, CSPO, CSD, CSP-SM, CSP-PO (ScrumAlliance.org) Certification Profile Link- https://www.scrumalliance.org/community/profile/mhaque13 Currently working as Lead Team (Application Architecture) at Raven Systems Ltd. Passion for software development especially agile practices such as TDD with in depth knowledge of Object Oriented Programming, SOLID Principles, Gang of Four Design Patterns, Some Enterprise Application Architectural Patterns. Over 8 years of software development experience ASP.NET. Has the ability to understand and transform complex business requirements into software ensuring applications are delivered on time. Also experience in non Microsoft .NET technologies such as Dapper.Net, Git, Structure Map & Angular, Bootstrap, HTML-5, CSS-3 etc.

Leave a Reply

Your email address will not be published. Required fields are marked *