Entity Framework Initial Entity Framework Code First Migration Step by Step


Example

  1. Create a console application.
  2. Install EntityFramework nuget package by running Install-Package EntityFramework in "Package Manager Console"
  3. Add your connection string in app.config file , It's important to include providerName="System.Data.SqlClient" in your connection.
  4. Create a public class as you wish , some thing like "Blog"
  5. Create Your ContextClass which inherit from DbContext , some thing like "BlogContext"
  6. Define a property in your context of DbSet type , some thing like this :
public class Blog 
{
    public int Id { get; set; }

    public string Name { get; set; }
}
public class BlogContext: DbContext
{
    public BlogContext(): base("name=Your_Connection_Name")
    {
    }

    public virtual DbSet<Blog> Blogs{ get; set; }
}
  1. It's important to pass the connection name in constructor ( here Your_Connection_Name)
  2. In Package Manager Console run Enable-Migration command , This will create a migration folder in your project
  3. Run Add-Migration Your_Arbitrary_Migraiton_Name command , this will create a migration class in migrations folder with two method Up() and Down()
  4. Run Update-Database command in order to create a database with a blog table