Detect missing migrations in Entity Framework Core
Entity Framework Core allows to update the database schema using migrations. The migrations are created manually by running a CLI command. It's easy to forget to create a new migration when you change the model. To ensure the migrations are up-to-date, you can write a test that compares the current model with the snapshot model:
C#
[Fact]
public async Task EnsureMigrationsAreUpToDate()
{
await using var dbContext = new SampleDbContext();
// Get required services from the dbcontext
var migrationModelDiffer = dbContext.GetService<IMigrationsModelDiffer>();
var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>();
var modelRuntimeInitializer = dbContext.GetService<IModelRuntimeInitializer>();
var designTimeModel = dbContext.GetService<IDesignTimeModel>();
// Get current model
var model = designTimeModel.Model;
// Get the snapshot model and finalize it
var snapshotModel = migrationsAssembly.ModelSnapshot?.Model;
if (snapshotModel is IMutableModel mutableModel)
{
// Forces post-processing on the model such that it is ready for use by the runtime
snapshotModel = mutableModel.FinalizeModel();
}
if (snapshotModel is not null)
{
// Validates and initializes the given model with runtime dependencies
snapshotModel = modelRuntimeInitializer.Initialize(snapshotModel);
}
// Compute differences
var modelDifferences = migrationModelDiffer.GetDifferences(
source: snapshotModel?.GetRelationalModel(),
target: model.GetRelationalModel());
// The differences should be empty if the migrations are up-to-date
Assert.Empty(modelDifferences);
}
The previous code is inspired by this comment on the GitHub issue: https://github.com/dotnet/efcore/issues/26348#issuecomment-1535156915.
Do you have a question or a suggestion about this post? Contact me!
Enjoy this blog?
💖 Sponsor on GitHub