Skip to main content

Entity Framework Code First migrations

In this blog post we are going to learn about entity code first migrations. Entity Framework code first approach will allow you to define model classes as per the domain requirements via POCOs. Hence you have complete control over classes are written. But as application grows and there are some new features to be added and  your classes will change. Entity Framework Code Migrations allows you to handle this migrations.

As we all now that Entity Framework Code First approach allows you to create database based on your classes created. It’s provide you three types of initializers.

CreateDatabaseIfNotExist: This is the default initializer which will create classes if database not exists.

DropCreateDatabasesWhenModelChanges: This initializer is only good when you don’t concern about your database records. If there is any change in class then it will match database will classes and if there is any difference then it will drop and create a new database.

DropCreateDatabaseAlways: This initializer will always create new database whether database exist or not. If database exist then it will drop that database and create it again.

Due to this initializers if we change our model classes and according to that your database will drop  that is where Entity Framework code migrations will help. It will allows you to update your database based on classes change without dropping database.

Walkthrough of Entity Framework Code First Migration:


For this walkthrough we are going to create a sample console application. I have create my entity like following.

namespace EntityCodeFirstMigrations
{
    public class Customer
    {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Now it's time to add entity framework to console application. I have added entity framwork  to console application via Tools – > Library Package Manager –> Package Manager Console and via running following command.

Install-Package EntityFramework

Now it’s time to create a blank database called Customer.

database-creation-entity-framework-code-firstmigration

After adding EntityFramework, I have created a my CustomerDataContext like below.

using System.Data.Entity;

namespace EntityCodeFirstMigrations
{
    public class CustomerDataContext : DbContext
    {
        public CustomerDataContext()
            : base("CustomerConnectionString")
        {

        }
        public DbSet<Customer> Customers { get; set; }
    }
}
After creating a code following is code I have written in Console application main method.

using System;
namespace EntityCodeFirstMigrations
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var dbContext = new CustomerDataContext())
            {
                //Adding a customer
                dbContext.Customers.Add(
                    new Customer { 
                        FirstName="Vishal",
                        LastName="Vadgama"
                    }
                );
                dbContext.SaveChanges();

                //Displaying Customer
                foreach (Customer customer in dbContext.Customers)
                {
                    Console.WriteLine(customer.FirstName);
                    Console.WriteLine(customer.LastName);
                    Console.WriteLine("---------------");
                }
            }
        }
    }
}
This code is pretty self explanatory. Here I have created a object of customer and added into the database with save changes method and then I have written a for loop for displaying customer values. Now your run the application it will show output as follows.

console-application-entity-framework-code-first-migration

So everything works fine. Now Let’s see our database. You can see there are two created. _MigrationHistory and Customer.

database-entity-framework

So you can see that Customer table create with three columns. Now our requirement changes a little bit. Now we want to add a Company field in Customer like so our mode class change like following.

namespace EntityCodeFirstMigrations
{
    public class Customer
    {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Company { get; set; }
    }
}

So now if we run the application it will delete database and create it again. So let’s see how migration can be useful. Let’s first get familiar with two command of entity framework and then we will create a migration for company.

Enable-Migrations: This will enable migrations for the application and database.

Add-Migration : This command will scaffold the next migration based on changes you have made to your model since the last migration was created.

Update-Database: Will apply pending migration to database.

I have run following command in package-manager console.

Enable-Migrations

Add-Migration AddCompanyField

So it will create a migration folder and AddCompanyField Class. I have written code for it as following.

using System.Data.Entity.Migrations;

namespace EntityCodeFirstMigrations.Migration
{
    public partial class AddCompanyField : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.Customers", "Company", c => c.String());
        }
        public override void Down()
        {
            DropColumn("dbo.Customers", "Company");
            base.Down();
        }
    }
}
Now it's time to run update-database command like in package manager console.

Update-Database

And it will create a company URL in Customer Table.

Code-First-Migrations

You can find source code for this application on github at following location.

https://github.com/dotnetjalps/Entity-Framework-Code-First-Sample

That’s it. Hope you like it. Stay tuned for more..

Comments

  1. Thanks jalpesh, very easy explanation.Would like to see more articles on entity framework.

    ReplyDelete
    Replies
    1. I have already written few and continue to write more!! thanks for appreciation

      Delete

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.



Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.



Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO; using Microsoft.Asp…

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations: Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample asp.net core web application like following.



Once we select asp.net core application it will appear the following dialog.



Now w…

Solution: gulp is not recognized as internal or external command- Visual Studio

Recently, After Upgrading to the newer version of Gulp, I was getting this error.  After doing lots of  finding online and in my system I was able to figure out that Modules like Gulp does not installed to the path. So when you try to run it from the command line it was showing below error.
gulp is not recognized as internal or external command How to solve : gulp is not recognized as internal or external command To solve this error we just need to create a new environment variable and set the NPM modules path there.

To create an environment variable,  Right click My Computer/ This Pc and click on properties.  It will open following windows.



Go to Advance System Settings and it will open system properties windows like below.



Click on Environment Variables it will open an environment and system variables windows like below.



Click on new System variable and put NODE_PATH in system variable name and %AppData%\npm\node_modules into the variable value like below.



Click on Ok. That’s it. N…