Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In EF Core, how to check whether a migration is needed or not?

I am using Entity Framework Core in an Xamarin.iOS application.

In my core project that contains code (.netstandard 2.0) that is shared between the iOS application and other applications, I would like to know if a migration is needed so that I can perform some other operations as well.

Here is the context:

public void Initialize()
{
   using (var dbContext = new MyDbContext(m_dbContextOptions))
   {
       --> bool isNeeded = demoTapeDbContext.Database.IsMigrationNeeded()

       demoTapeDbContext.Database.Migrate();
   }
}

The closest I have found is calling the method GetPendingMigrationsAsync() and check the amount of pending migrations but I am unsure whether it is the safest way to do such check in Entity Framework:

public async Task InitializeAsync()
{
   using (var dbContext = new MyDbContext(m_dbContextOptions))
   {
       bool isMigrationNeeded = (await demoTapeDbContext.Database.GetPendingMigrationsAsync()).Any();

       demoTapeDbContext.Database.Migrate();
   }
}
like image 305
Kzrystof Avatar asked Jan 24 '19 23:01

Kzrystof


People also ask

How do I get rid of migration?

Delete your Migrations folder. Create a new migration and generate a SQL script for it. In your database, delete all rows from the migrations history table. Insert a single row into the migrations history, to record that the first migration has already been applied, since your tables are already there.


2 Answers

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.

like image 169
DavidG Avatar answered Sep 28 '22 03:09

DavidG


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();
        }
        ...
like image 28
Ogglas Avatar answered Sep 28 '22 03:09

Ogglas