Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop database if model changes in EF Core without migrations

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.

like image 968
Rey Cruz Avatar asked Aug 30 '16 19:08

Rey Cruz


People also ask

What is migrations in Entity Framework?

The migrations feature in EF Core provides a way to incrementally update the database schema to keep it in sync with the application's data model while preserving existing data in the database.

What is database EnsureCreated?

EnsureCreated. EnsureCreated will create the database if it doesn't exist and initialize the database schema. If any tables exist (including tables for another DbContext class), the schema won't be initialized.

What is Entity Framework and why we use it?

The Entity Framework enables developers to work with data in the form of domain-specific objects and properties, such as customers and customer addresses, without having to concern themselves with the underlying database tables and columns where this data is stored.


2 Answers

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();
}
like image 135
bricelam Avatar answered Sep 28 '22 03:09

bricelam


Initializers don't 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

like image 43
Steve Greene Avatar answered Sep 28 '22 03:09

Steve Greene