Code First Migrations In Entity Framework Step By Step

Here are the steps

Model Classes

Suppose you have the following two entities within your application.

public class Employee
{
    [Key]
    public int Id
    {
        get;
        set;
    }
    [Required]
    public string Code
    {
        get;
        set;
    }
    [Required]
    public string Name
    {
        get;
        set;
    }
    [Required]
    public string OptionType
    {
        get;
        set;
    }
    public bool Active
    {
        get;
        set;
    }
    public string Notes
    {
        get;
        set;
    }
    public ICollection<OptionsHistory> OptionsHistories
    {
        get;
        set;
    }
}

public class OptionsHistory
{
    [Key]
    public int Id
    {
        get;
        set;
    }
    public string Code
    {
        get;
        set;
    }
    public string Name
    {
        get;
        set;
    }
    public string OptionType
    {
        get;
        set;
    }
    public bool Active
    {
        get;
        set;
    }
    public string Notes
    {
        get;
        set;
    }
    public int OptionId
    {
        get;
        set;
    }
    public string OptionsVersion
    {
        get;
        set;
    }
    public Options Options
    {
        get;
        set;
    }
}

Here [Key] decorated column is a primary key column.

Mapping details

DataContext class and Fluent API mapping details for the above two entities are given below.

public class OptionCodeContext : DbContext
{
    public OptionCodeContext() : base("name=DbConnectionString")
    {

    }
    public DbSet<Options> options
    {
        get;
        set;
    }
    public DbSet<OptionsHistory> optionsHistories
    {
        get;
        set;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Options>().HasKey(p => p.Id);

        modelBuilder.Entity<Options>().Property(c => c.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        modelBuilder.Entity<OptionsHistory>().HasKey(b => b.Id);

        modelBuilder.Entity<OptionsHistory>().Property(b => b.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        modelBuilder.Entity<OptionsHistory>().HasRequired(p => p.Options)
            .WithMany(b => b.OptionsHistories).HasForeignKey(b => b.OptionId);

        base.OnModelCreating(modelBuilder);
    }
}

Connection String

And, your database connection string is given below

<add name="DbConnectionString" connectionString="data source=SampleDataSource;initial catalog=OptionsCode;integrated security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

Visual Studio package manager console

To create the database for these two entities within your application, go to the Package Manager Console option as shown below

Library Package Manager

Creating new database


Running Commands

Run the following command to configure migrations within your project and to create a new database.

  • Enable migrations
    Enable-Migrations
  • Create migration
    Add-Migration MigrationsName
  • Create upgrade/downgrade script
    Update-Database

When you run the above-listed command on the Package Manager Console windows one by one then

  • Firstly, a Migrations folder will be added to your applications having Configuration.cs file for the Migrations configuration setting.
    Migration
  • Secondly, a class file will be created having a name suffix as MigrationsName followed by an underscore and a unique generated number. This file will have all the entities to be created in the database.
  • Thirdly, a new database will be created having the initial catalog name (initial catalog = YourDBName) as given in your connections string.

Suppose you have added one more class named Customer into your data model classes

Now for updating the database with new changes run the following commands.

  1. Create migration
    Add-Migration MigrationsName
  2. Create upgrade/downgrade script
    Update-Database

When you run the above-listed command on the Package Manager Console windows one by one, then

Firstly, a class file will be created having a name suffix as MigrationsName followed by an underscore and a unique generated number. This file will have all the entities to be created or updated in the database.

solution

Undo/Rollback a Migration

You can also Undo/Rollback specific migrations by using the following commands

  1. Rollback to specific migrations
    Update-Database -TargetMigration:MigrationsName
    
  2. Rollback all migrations
    Update-Database -TargetMigration:0


Similar Articles