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.");
}
}
}
You can do this...
```c#
using Microsoft.EntityFrameworkCore.Infrastructure;
...
if(_context.GetService
{
...
}
```
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"
Most helpful comment
A better alternative might be this:
C# dbContext.GetService<IDatabaseProviderServices>() .InvariantName == "Microsoft.EntityFrameworkCore.SqlServer"