Entity-framework – EF: Automatic migrations are running when disabled

database-migrationentity-frameworkentity-framework-5

I'm trying to update the database on a build server, and it's failing because it's trying to run automatic migrations, even though they're disabled. The database already exists and I just need to apply the latest migration. Here's my context:

public sealed class Configuration : DbMigrationsConfiguration<CableSenseInstanceConfiguratorContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }
}

I've got a bunch of migration files I've created manually, here's the latest one:

public partial class Settings : DbMigration
{
    public override void Up()
    {
        AddColumn("dbo.MasterInstances", "Settings", c => c.String());
    }

    public override void Down()
    {
        DropColumn("dbo.MasterInstances", "Settings");
    }
}

If I then manually update the database from the package manager console, I see it tries to run an automatic migration (which fails because the table already exists):

Applying code-based migrations: [201204200805145_NoMoreCerts, 201210311451543_SuperUsers, 201301041036414_Settings, 201301041128583_Settings2].
Applying code-based migration: 201204200805145_NoMoreCerts.
Applying automatic migration: 201204200805145_NoMoreCerts_AutomaticMigration.

My __MigrationHistory table just has the one entry for the initial creation. How can I stop it from doing the automatic migrations?

Best Answer

Check out the answer from jjslagace here:

Update-Database tries to do an automatic migration even with automatic migrations disabled

You are building your migrations manually. My guess is entity framework wants to add something that you don't have in your migration script, or it wants to name columns differently etc. EF has a brain, and that brain is fairly simple. It's expecting things to be a certain way unless you tell it otherwise using fluent (not by manually creating/tweaking migration files). From the answer on the question above it sounds like sometimes that results in the issue you are seeing.

Long story short don't build the migration files manually. Instead run the add-migrations command. This will create the migration for you and you can see what EF is expecting to do before it's applied to your database (because sometimes it's stupid). If you need to override what EF is generating for you add a fluent mapping in your DBContext class by overriding OnModelCreating. Then just run add-migration again with the -force option. Here is a good reference for using the Fluent API to custimize EF mappings. Rinse and repeat until you get the migration you are looking for then run update-database.

Hope that helps!