Check if applied migrations match the DbContext?

跟風遠走 提交于 2020-05-13 02:42:51

问题


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:


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!");



回答2:


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);
  }
}


来源:https://stackoverflow.com/questions/47091587/check-if-applied-migrations-match-the-dbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!