Dot-Net-Core
檢查應用的遷移是否與 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); } }