检查应用的迁移是否与 DbContext 匹配?
Check if applied migrations match the DbContext?
我想创建一个单元测试以确保开发人员不会在没有相应迁移的情况下提交模型更改。
如何测试数据库是否与 DbContext 匹配?
您可以利用一些较低级别的迁移组件来执行此操作:
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!");
根据@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);
}
}
我想创建一个单元测试以确保开发人员不会在没有相应迁移的情况下提交模型更改。
如何测试数据库是否与 DbContext 匹配?
您可以利用一些较低级别的迁移组件来执行此操作:
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!");
根据@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);
}
}