Database crash if model changes in EF Core without migration

In a previous version of the entity infrastructure, you could recreate the database if the model changed using some DropDatabseIfModelChanges classes and other related classes. In EF7 or EF Core, I do not know how to do this. Starting the migration several times gives problems, and at the beginning of the project I need to constantly change models.

+4
source share
2 answers

There is currently no easy way to implement DropDatabseIfModelChangesin EFCore. EF6 worked by storing a snapshot of your model in a table __MigrationHistoryand comparing it with the current model. Such information is not stored in EnsureCreatedthe EFCore.

To emulate the behavior in EFCore, you can manually save the model hash whenever you create a database in EFCore, check the hash at startup, and delete and recreate the database if it has changed.

var currentHash = MyHashingFunction(db.Model);

if (db.GetService<IRelationalDatabaseCreator>().Exists()
    && !db.Set<ModelHash>().Any(mh => mh.Value == currentHash))
{
    // Drop if changed
    db.Database.EnsureDeleted();
}

if (db.Database.EnsureCreated())
{
    // Insert hash if created
    db.Add(new ModelHash { Value = currentHash });
    db.SaveChanges();
}
+4
source

Initializers do not exist in EF Core . Instead, you can call EnsureCreated (and possibly EnsureDeleted):

public class MyCountriesContext : IdentityDbContext<ApplicationUser>
{
  public MyCountriesContext()
  {
    Database.EnsureCreated();
  }

  public DbSet<Visit> Visits { get; set; }

  protected override void OnModelCreating(ModelBuilder builder)
  {
    builder.Entity<Visit>().Key(v => v.Id);

    base.OnModelCreating(builder);
  }
}

See https://wildermuth.com/2015/03/17/A_Look_at_ASP_NET_5_Part_3_-_EF7

+1
source

Source: https://habr.com/ru/post/1653045/


All Articles