如何使用SQL Server而不是内存中仅运行迁移

时间:2016-11-03 10:19:20

标签: entity-framework dbcontext entity-framework-core ef-migrations

我正在使用带有迁移的SQL Server的Entity Framework Core。我也在集成测试中使用In-Memory和SQL-Lite内存数据库连接。

如何在使用SQL Server连接时才运行迁移?我无法看到基于DbContext检测数据存储类型的方法。

3 个答案:

答案 0 :(得分:2)

您可以使用MigrationBuilder.ActiveProvider属性来确定是否在迁移中执行Up方法:

protected override void Up(MigrationBuilder migrationBuilder)
{
    if (migrationBuilder.ActiveProvider == "Microsoft.EntityFrameworkCore.SqlServer")
    {
        CreateTable(....
    }
}

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/providers#one-migration-set

答案 1 :(得分:1)

这是一个选项......

if (db.GetService<IDatabaseProviderServices>()
    .InvariantName == "Microsoft.EntityFrameworkCore.SqlServer")
{
    db.Database.Migrate();
}

答案 2 :(得分:0)

EntityFramework Core内置了依赖注入。您可以通过将其作为服务来检查数据库提供程序,如下所示:

if (dbContext.GetService<IDatabaseProviderServices>() is SqlServerDatabaseProviderServices)
{
    await dbContext.Database.MigrateAsync();
}