1
votes

Background: Everything was going smoothly until I created a new Model class and changed one of existing Model classes. And I Migrated successfully.

The situation is I have to run add-migration and update-database every time I build my project to avoid this exception. I have no idea what's going on. Please help.

Additional: automatic-migration is set to true. I checked the _MigrationHistory table and every migration is present there

1
Add OnModelCreating to your YourDbContext - Divyang Desai
Would you please explain a bit more. I am working on an existing project which already implemented that method with lot of codes like this: modelBuilder.Entity<account>() .HasMany(e => e.useraccount) .WithRequired(e => e.account) .WillCascadeOnDelete(false); Do i need to manually add my new model class here ? - Taz Uddin

1 Answers

4
votes

You have to add code to your DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Database.SetInitializer<YourDbContext>(null);
    base.OnModelCreating(modelBuilder);
} 

EDIT :
When a model is first created, we run a DatabaseInitializer to do things like create the database if it's not there or add seed data.

The default DatabaseInitializer tries to compare the database schema needed to use the model with a hash of the schema stored in an EdmMetadata table that is created with a database (when Code First is the one creating the database).

Existing databases won’t have the EdmMetadata table and so won’t have the hash and the implementation today will throw if that table is missing.

We'll work on changing this behavior before we ship the fail version since it is the default. Until then, existing databases do not generally need any database initializer so it can be turned off for your context type by calling:

Database.SetInitializer<YourDbContext>(null);