Friday, 21 November 2014

Entity Framework Code First (Data Migrations) PART-2


Continuing on the data migration steps, we have few more options available.
If database already exists and you run your application what will happen?

So for this purpose we have different database initialization strategies:

CreateDatabaseIfNotExists: Default one. will create new database if not already exists.

DropCreateDatabaseWhenModelChanges: If you have no concern with your db records. If you make any change in domain classes, then this will first check into database if found change in DB tables and classes then it will first drop and then create new database again.

DropCreateDatabaseAlways: This will always create database whether it already exists or not. If already exists then drop first and then re-create again.

Custom DB Initializer: You can also create your own custom initializer, if any of above could not satisfy your requirement.


Turn off DB Initializer in code first

You can also turn off application initializer , for example in production environment you don't want to lose existing data.

public class DataContext : DbContext
{
    public DataContext()
        : base("ExampleConnectionString")
    {
        //Disable initializer
        Database.SetInitializer<DataContext>(null);
    }
    public DbSet<Student> Students { get; set; }
    public DbSet<Employee> Employees { get; set; }
}

Turn off initializer in config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="DatabaseInitializerForType ExampleDataLayer.DataContext, ExampleDataLayer"
         value="Disabled" />
  </appSettings>
</configuration>

Hope you like this !!

No comments:

Post a Comment