检查应用的迁移是否与DbContext匹配?

时间:2017-11-03 08:45:06

标签: .net-core entity-framework-core ef-core-2.0

我想创建一个单元测试,以确保没有相应的迁移,开发人员不会提交模型更改。

如何测试数据库是否与DbContext匹配?

2 个答案:

答案 0 :(得分:3)

您可以利用一些较低级别的迁移组件来执行此操作:

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

答案 1 :(得分:0)

基于@bricelam的回答,我创建了一种通用方法来测试应用的迁移。

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