Web
Analytics
Entity Framework migration with example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Entity Framework migration with example

This feature is introduced in EF 5 to overcome the problem of database Datainitilzers(Data was lost). We can make changes in database and able to revert back using migrations techniques.

Example:

Step 1. First we will create two classes named Category and Product

namespace FluentAPIEF.Models

{

    public class Category

    {

        [Key]

        public int CategoryId { get; set; }

        public string Name { get; set; }

    }

}

namespace FluentAPIEF.Models

{

    public class Product

    {

[Key]

        public int ProductId { get; set; }

        public string ProductName { get; set; }

        public decimal UnitPrice { get; set; }

        public int CatId { get; set; }

        [ForeignKey(“CatId”)]

        public virtual Category category { get; set; }

    }

}

 

Step 2. Install Entity Framework using Package Manager Console

install-package entityframework

Step3: Define connection string in web .config file

<connectionStrings>

    <add name=”conn” connectionString=”server=.\sqlexpress;database=MVCEx;integrated security=SSPI” providerName=”System.Data.SqlClient”/>

 

  </connectionStrings>

 

Step 4. Create Data Context class in Model folder

public class DataContext:DbContext

    {

        public DataContext():base(“conn”)

        {

 

        }

        public DbSet<Category> Categories { get; set; }

        public DbSet<Product> Products { get; set; }

 

    }

Using Data Initilizer , we lost tables date that is why we used datamigration techniques. We also called it Entity framework data migration.

Step 5. Open Package manager console write following command

Enable-migrations

Above command will create a folder named Migrations and add a class file “Configuration.cs”

Migration is also used for rollback data facility

Seed Method:  Seed Method is used for  Master Data Table.

Step 6. Run another command

Add-migration [initial]

After run  this command some .cs file also created in migration folder .One of cs file have two methods Up() and Down()  two methods .Up methods is used to create database tables in database and down method is used to rollback database changes

public partial class initial : DbMigration

    {

        public override void Up()

        {

            CreateTable(

                “dbo.Categories”,

                c => new

                    {

                        CategoryId = c.Int(nullable: false, identity: true),

                        Name = c.String(),

                    })

                .PrimaryKey(t => t.CategoryId);

 

            CreateTable(

                “dbo.Products”,

                c => new

                    {

                        ProductId = c.Int(nullable: false, identity: true),

                        ProductName = c.String(),

                        UnitPrice = c.Decimal(nullable: false, precision: 18, scale: 2),

                        CatId = c.Int(nullable: false),

                    })

                .PrimaryKey(t => t.ProductId)

                .ForeignKey(“dbo.Categories”, t => t.CatId, cascadeDelete: true)

                .Index(t => t.CatId);

 

        }

 

        public override void Down()

        {

            DropForeignKey(“dbo.Products”, “CatId”, “dbo.Categories”);

            DropIndex(“dbo.Products”, new[] { “CatId” });

            DropTable(“dbo.Products”);

            DropTable(“dbo.Categories”);

        }

    }

Still database is not created tables

Step 7. Run following command to make changes in database

update-database –verbose

Tables(__MigrationHistory, Categories and Products) will be created in database.

mig

In Migration History table MigrationId field have date when database changes has been done using code migration.

Note: Now we will see that how we can update database and rollback in database.

Step 8. Add a new class Customer

public class Customer

    {

        [Key]

        public int CustomerId { get; set; }

        public string CustomerName { get; set; }

    }

Step 9. Make following changes in DataContext Class

  public class DataContext:DbContext

    {

        public DataContext():base(“conn”)

        {

 

        }

        public DbSet<Category> Categories { get; set; }

        public DbSet<Product> Products { get; set; }

        public DbSet<Customer> Customers { get; set; }

 

    }           

Step 10: Run Follwing Command

Add-migration [AddCustomer]

It will another class which have also Up() and down method

Step 11. Again run command

Update-database –verbose

This command will create customers table and update migration table

Here you can see that new record has been inserted which have complete details of new migration.

To rollback changes let us execute another command

Update-database –targetmigration:’initial

Here “initial” is my example migration name.

After implementation of this command Customer table will be deleted and migration table also updated where last added migration record will be removed.

Note: This command will not remove migration in solution explorer

Now Let us see that how we can insert data in Master table using seed methodin Configuration.cs

protected override void Seed(FluentAPIEF.Models.DataContext context)

        {

 

            Category cat1 = new Category { Name = “Soap” };

            Category cat2 = new Category { Name = “Oil” };

            Product prd1 = new Product { ProductName = “Dettol”, UnitPrice = 30.50M, category = cat1 };

            Product prd2 = new Product { ProductName = “Cinthol”, UnitPrice = 20.40M, CatId = 1 };

            context.Categories.Add(cat2);

            context.Products.Add(prd1);

            context.Products.Add(prd2);

 

            }

Step 12: Run Command again

Update-database –verbose

This command will add data in Category and Product tables.