entity-framework.net-coreentity-framework-migrations

Test for schema changes in Entity Framework migration


Context

I'm working a pipeline to manage a dot net core project. In my pipeline, at the build stage I run dotnet ef migrations script --context "MyDbContext" --project "./MySolution/MyDataProject/" --output "./migrationScript.sql" --idempotent to generate scripts which can later be run against the various test, staging, and production environments databases to sync the schema (I use the same approach in non-production environments as in production to ensure those scripts are tested).

It's my understanding that these scripts aren't generated based on the database context, but rather use the migrations which are already defined in the project; with those migrations having been defined via the add command (e.g. dotnet ef migrations add vNext --context "MyDbContext" --project "./MySolution/MyDataProject/"). As such, it's possible that a developer may make changes to the data model, forget to run the migrations add command to add a new migration, and thus create a solution that will fail to update the schema.

Question

Is there a way to test if the migrations are in sync with the code / if a new migration is needed?

Thoughts around Solutions

I'd hoped that by running dotnet ef migrations add when there are no changes to the dbContext there would be no output; so I could test for the presence of a new file and have the pipeline terminate if this had been missed (checking nothing into git; so the new migration isn't persisted / it's left for the developer to manually rerun this).

Looking at the available options, there's only add, remove, list, and script; so nothing obvious for performing this check.

I could run the add command before the script command in my pipeline to ensure it's been run; but then there may be issues with future runs, since if the added migration isn't pushed to git, the next iteration won't be aware of this migration. If I were to push this new migration to git that resolves that issue; but then creates a new issue that every build creates a new migration, so we'll have a lot of redundant clutter / this approach won't be sustainable.

The best solution I can think of is to run the add command, then inspect the generated scripts to see if the Up or Down methods have anything in the functions' bodies; but that feels hacky; and I'm not certain it's enough (e.g. do the methods in the .Designer.cs file ever change without producing anything in Up/Down in the .cs file?).

I'm sure MS would have created something in the toolset for this; but I'm struggling to find it. Thank-you in advance for any help.

Existing / Similar Answers


Solution

  • Something that appears to work with a few simple test cases I've tried is to add a test migration, and then check if the <ContextName>ModelSnapshot.cs file has changed in the migrations directory.

    That file only appears to change when the core migration has been amended.