tika tika - 3 years ago 171
ASP.NET (C#) Question

dotnet ef migrations automation: Detect changes for migrations

I use the following CLI for DB Migrations:

  1. dotnet ef migrations add <Name-of-Migration>

  2. dotnet ef database update

However, I am looking for a way for this to happen automatically: when a change in the Model is detected.

So far, I have been able to eliminate Step 2 by doing the following in Startup.cs:

private void SetupDatabase(IApplicationBuilder app)
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
//Migate any pending changes:

This migrates any pending changes created by doing:
dotnet ef migrations add <Name-of-Migration>

but it does not add migration for any changes in the model. How do I automate this
migrations add

Answer Source

Its not possible to move the first step of generating a migration automatically from code (at the moment at least), a design decision that I personally agree with. The second step can be automated as you also found out.

Why automatic model change monitoring to generate and update database automatically might backfire sometimes(in my humble opinion):

  • Its good to confirm that a model change is deliberate and was not a result of some leftover code while changes were being made, something that can happen and automating the complete process might slip such changes to DB.
  • The migrations that get generated are not always optimized and/or fail due to some data constraints or similar issues and hence should be reviewed.
  • Even update database has timed out for us on production data in some cases when there was loads of data the migration was handling. We had to then manually run it remotely and restart the server.

The above might not apply to everyone, but thought should share.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download