Attributes in EF Core migrations

September 8th 2023 EF Core C#

Recently, I was tasked with troubleshooting an EF Core migrations issue in a codebase I was not familiar with. The problem was that the Update-Database command didn't detect the migration in the project. It behaved as if the migration file wasn't present at all:

PM> Update-Database
Build started...
Build succeeded.
No migrations were applied. The database is already up to date.
Done.

I checked. No migrations were applied to the database. The __EFMigrationsHistory table was empty.

After taking a closer look at the project, I noticed that there was no .Designer.cs file accompanying the migrations file. Although the BuildTargetModel method in the .Designer.cs file isn't used most of the time, it's still needed for some operations, and it's not a good idea to delete it.

Even more importantly, the partial class in the file contains two attributes which are used to find the migrations in the project:

[DbContext(typeof(PersonDbContext))]
[Migration("20230812093458_InitialCreate")]

The DbContext attribute identifies the DbContext class that the migration belongs to. The Migration attribute identifies the migration class as a migration and assign it an identifier that is written to the __EFMigrationsHistory table. When the migration is generated, the identifier matches the filename (without the extension), but the value could be anything, as long as it is unique across all the migrations for the given database context.

For a migration without its .Designer.cs file, it's best to just delete the migration and regenerate it with a Add-Migration command, which will also generate the missing .Designer.cs file. However, for the Update-Database command to detect the already present migration file, it's enough to add the missing two attributes to the class in the migration file:

[DbContext(typeof(PersonDbContext))]
[Migration("20230812093458_InitialCreate")]
public partial class InitialCreate : Migration

After doing that, the command should apply the migration as expected:

PM> Update-Database
Build started...
Build succeeded.
Applying migration '20230812093458_InitialCreate'.
Done.

You can check a sample project in my GitHub repository to try that out yourself. The migration in the last commit is already fixed. But in the previous commit, the attributes are missing, therefore the migration is not detected.

Deleting auto-generated files is in general a bad idea, and you should avoid doing it, at least until you learn what that code does and whether it is really safe to delete it. This post explains what can happen if you delete the designer files for the generated EF Core migrations and how you can fix the resulting issue.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License