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