Search code examples
c#entity-frameworkef-code-firstentity-framework-migrations

Entity Framework, Automatic apply Migrations


I am using Entity Framework Code First approach with AutomaticMigrationsEnabled = true:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<DbContext, MigrateDBConfiguration>());
//////////////////////////////////

public class MigrateDBConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<DbContext>
{
    public MigrateDBConfiguration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }
}

The first run of the project creates the database and tables as expected. After changing my model by adding or dropping fields, I ran Add-Migration. The Migration class was generated but after running the project this exception occurs:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: The model backing the 'DBContext' context has changed since the database was created.

EDIT: Per the guidance in the answer of arturo menchaca I changed my code like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<DBContext, MigrateDBConfiguration<DBContext>>());

...

After the change this exception is occurring:

There is already an object named 'MyTable' in the database.

How can I apply my database migration?


Solution

  • Finally, I found a solution to my problem. I call this method in each application start :

    public void InitializeDatabase(DataAccessManager context)
    {
        if (!context.Database.Exists() || !context.Database.CompatibleWithModel(false))
        {
            var configuration = new DbMigrationsConfiguration();
            var migrator = new DbMigrator(configuration);
            migrator.Configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");
            var migrations = migrator.GetPendingMigrations();
            if (migrations.Any())
            {
                var scriptor = new MigratorScriptingDecorator(migrator);
                var script = scriptor.ScriptUpdate(null, migrations.Last());
    
                if (!string.IsNullOrEmpty(script))
                {
                    context.Database.ExecuteSqlCommand(script);
                }
            }
        }
    }