1
votes


I use EF 6 and code first in a project
I try to understand using 'enable-migrations' command.
DbContext and Initializer examples are in simplest form like below .

When I give the command 'enable-migrations'
package-manager console outputs an error like below :

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.

But If I do not call InitializeDatabase();method from MyDbContext constructor no error occures and no data imports or seed method does not run.
Only database creates.

I want to learn what's the reason and what's the mean of this error If I use InitializeDatabase() method.
Thank you

public class MyDbContext : DbContext
{
    public MyDbContext():base("TestDb")
    {
        Database.SetInitializer(new DbContextInitializer());
        InitializeDatabase();
    }

    protected virtual void InitializeDatabase()
    {
        if (!Database.Exists())
        {
            Database.Initialize(true);
        }
    }

    public DbSet<TestModel> TestModels { get; set; }
}

public class DbContextInitializer : CreateDatabaseIfNotExists<MyDbContext>
{
    protected override void Seed(MyDbContext context)
    {
        base.Seed(context);
        context.TestModels.Add(new TestModel() {
            Name = "Lorem",
            Surname = "Ipsum"
        });
    }
}
1

1 Answers

2
votes

Your initializer is inheriting from CreateDatabaseIfNotExists which is not a logical choice for migrations. You have some pending model changes that are not being applied because the model has changed and your initializer is only going to run when the database does not exist.

You could delete your database so it reinitializes with the changes, or switch your initializer to MigrateDatabaseToLatestVersion. Here is a good article on initializers and seeding.