In EF Core, how to check whether a migration is needed or not?
You are correct that the GetPendingMigrationsAsync
method is what you should use. From the docs:
Asynchronously gets all migrations that are defined in the assembly but haven't been applied to the target database.
If you look at the code, you can trace how it works. If gets all of the migrations defined in your assembly and removes the ones it finds by querying the database.
I use the following code in DbInitializer
:
public static class DbInitializer
{
public static void Initialize(ApplicationDbContext context)
{
if(context.Database.GetPendingMigrations().Any()){
context.Database.Migrate();
}
...