DotnetSparrow
DotnetSparrow

Reputation: 27996

model and table change error EF 4.1

I have following model in my MVC3 application and I am using entity frame 4.1 code first.

public class Movie
{
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    [Required]
    public string Director { get; set; }

    [CustomValidation(typeof(MovieValidator), "ValidateReleaseDate")]
    public DateTime ReleaseDate { get; set; }
}

Noe, If I remove the Required attribute from Title and Director and make them nullable in database (which is automatically created by EF code first from the above model), I get following error:

The model backing the 'MoviesDB' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

I have read that to solve this I have to do one of the following things:

1) remove db so that EF can recreate it

2) add following lines in context class: ( this doesnt work in context with EF 4.1, I added in application_start and it works. Why doesnt it work in context calss now ?)

Database.SetInitializer<MoviesDB>(
    new DropCreateDatabaseIfModelChanges<MoviesDB>());

3) match table with model ( my model is exactly same as table why I still get this error ?)

Please suggest answers of questions mentioned in point 2 and 3.

Thanks.

Upvotes: 1

Views: 1999

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

Setting initializer should work for example in context's constructor but it is not needed to call every time you initialized context - you need to do it only once so calling it during application startup is a good approach.

Manully updating database doesn't work if you are using automatic change detection (default behavior). When context creates a model it computes a hash from this model and compares it with value stored in EdmMetadata table (table is created first time the EF creates the database). If the value loaded from database is different EF either starts database recreation (if initializer is configured) or throws the exception you see. Manually changing the database will not modify hash stored in EdmMetadata so the model will still think that the database is unchanged.

This behavior can be removed by removing IncludeMetadataConvention:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    model.Conventions.Remove<IncludeMetadataConvention>();
}

After removing this convention EF will not use EdmMetadata table and will not check changes in the model. Updating the database will be completely up to you.

Upvotes: 3

Related Questions