Drop database if model changes in EF Core without migrations

asp.net-core c# ef-migrations entity-framework entity-framework-core

Question

In previous version of entity framework, one could recreate the database if the model changes, using some of the classes DropDatabseIfModelChanges and other related classes. In EF7 or EF Core i don't know how to do that. Run the migrations some times give problems and in the beginning of the project i need to change the models constantly.

1
8
8/30/2016 7:28:04 PM

Popular Answer

There's currently no easy way to implement DropDatabseIfModelChanges in EFCore. EF6 worked by storing a snapshot of your model in the __MigrationHistory table and comparing it to the current model. No such information is stored by EnsureCreated in EFCore.

To mimic the behavior in EFCore, you could manually store a hash of the model whenever you create the database in EFCore, check the hash on startup, and drop and re-create 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();
}
6
6/22/2017 3:36:44 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow