Check if applied migrations match the DbContext?

.net-core ef-core-2.0 entity-framework-core

Question

I want to create a unit test to ensure no developer will commit model changes without the corresponding migration.

How do I test that the database matches the DbContext?

1
6
11/3/2017 8:45:06 AM

Accepted Answer

You can leverage some of the lower-level Migrations components to do that:

var migrationsAssembly = db.GetService<IMigrationsAssembly>();
var differ = db.GetService<IMigrationsModelDiffer>();

var hasDifferences = differ.HasDifferences(
    migrationsAssembly.ModelSnapshot.Model,
    db.Model);

Assert.False(hasDifferences, "You forgot to add a migration!");
8
11/4/2017 12:00:48 AM

Popular Answer

Based on @bricelam's answer I created a generic method to test for applied migrations.

private static void ShouldMatchContext<T>()
  where T : DbContext
{
  using (var connection = new SqliteConnection("DataSource=:memory:"))
  {
    connection.Open();
    var builder = new DbContextOptionsBuilder<T>();
    var db = Activator.CreateInstance(typeof(T), builder.UseSqlite(connection).Options) as T;

    db.Database.EnsureCreated();

    var migrationsAssembly = db.GetService<IMigrationsAssembly>();
    var differ = db.GetService<IMigrationsModelDiffer>();

    bool hasDifferences = differ.HasDifferences(migrationsAssembly.ModelSnapshot?.Model, db.Model);

    Assert.False(hasDifferences);
  }
}


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