Entity Framework CodeFirst : Simple Migrations
When I change my model from let’s say
//Employee Entity
public class Employee
{
public int Id { get; set; }
public string FullName { get; set; }
}
to
//Employee Entity
public class Employee
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; } //New
}
Then I find a trouble. Either I have to drop create the whole database using
Database.SetInitializer<HRContext>(new DropCreateDatabaseIfModelChanges<HRContext>());
or I need to do it manually. But this deletes everything. Who wants that? No one. So I left with an option of reflecting only changes. Now in EF CodeFirst we call it as Migrations. This can be very in-depth customizable. I would like to show you the most simple option and you can take to complex user-defined approach based on your business need.
Step1: Run this command to your Package Manager Console
PM> Enable-Migrations
And the output would look like
After this two files will be created in project under a new folder “Migrations”
Then we need a small change there in the file configuration
internal sealed class Configuration : DbMigrationsConfiguration<ConsoleApplication1.HRContext>
{
Would be changed to
public sealed class Configuration : DbMigrationsConfiguration<ConsoleApplication1.HRContext>
{
And
AutomaticMigrationsEnabled = false;
would change to
AutomaticMigrationsEnabled = true;
Now the new Database initializer would look like,
Database.SetInitializer<HRContext>(new MigrateDatabaseToLatestVersion<HRContext, Migrations.Configuration>());
So the complete code would look like
public class Employee
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; } //New
}
public class HRContext : DbContext
{
public DbSet<Employee> Emps { get; set; }
}
class Program
{
static void Main(string[] args)
{
//Database.SetInitializer<HRContext>(new DropCreateDatabaseIfModelChanges<HRContext>());
Database.SetInitializer<HRContext>(new MigrateDatabaseToLatestVersion<HRContext, Migrations.Configuration>());
var emp = new Employee() { FullName = "Wriju Ghosh", Email = "some@contoso.com" };
using (var ctx = new HRContext())
{
//This would get me the database information
string strConnection = ctx.Database.Connection.ConnectionString;
Console.WriteLine(strConnection);
ctx.Emps.Add(emp);
ctx.SaveChanges();
foreach (var em in ctx.Emps)
{
Console.WriteLine(em.FullName);
Console.WriteLine(em.Email==null?"null":em.Email);
}
}
}
}
Namoskar!!!