Efcore: How to Only Run Migrations if Using SQL Server and not SqlLite/In-Memory

Created on 3 Feb 2017  路  3Comments  路  Source: dotnet/efcore

I'm using Entity Framework Core using SQL Server with migrations. I am also using the In-Memory and SQL-Lite In-Memory database connections in my integration tests. I use the code below to migrate my database at app startup so it has no performance impact.

How can I only run migrations when I am using a SQL Server connection? I have found the method below but that is using reflection. I can't see a way of detecting the type of data store based on a DbContext.

public static async Task InitializeDatabase(
    ApplicationDbContext applicationDbContext,
    ILogger<ApplicationDbContext> logger)
{
    var databaseCreator = applicationDbContext
        .Database
        .GetType()
        .GetTypeInfo()
        .GetProperty("DatabaseCreator")
        .GetValue(applicationDbContext.Database);
    if (databaseCreator is is SqlServerDatabaseCreator)
    {
        try
        {
            await applicationDbContext.Database.MigrateAsync();
            logger.LogInformation("Migrated database.");
        }
        catch (Exception exception)
        {
            logger.LogCritical(0, exception, "Failed to migrate database.");
        }
    }
}
closed-question

Most helpful comment

A better alternative might be this:
C# dbContext.GetService<IDatabaseProviderServices>() .InvariantName == "Microsoft.EntityFrameworkCore.SqlServer"

All 3 comments

You can do this...

```c#
using Microsoft.EntityFrameworkCore.Infrastructure;

...

if(_context.GetService() is SqlServerDatabaseCreator)
{
...
}
```

GetService<TService>() is an extension method that gives you access to all the underlying services that EF is using.

A better alternative might be this:
C# dbContext.GetService<IDatabaseProviderServices>() .InvariantName == "Microsoft.EntityFrameworkCore.SqlServer"

Was this page helpful?
0 / 5 - 0 ratings