注册EF上下文时指定每个环境的商店类型

时间:2015-08-04 14:16:00

标签: c# dependency-injection asp.net-core asp.net-core-mvc entity-framework-core

在Startup ConfigureServices期间注册EF上下文时,有没有办法指定在环境级别使用哪种商店类型?我不想仅仅为了切换商店类型而重新创建集成测试的启动类。

使用单一商店类型注册上下文

public void ConfigureServices(IServiceCollection services)
{
    var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNet5;Trusted_Connection=True;";

    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
 }

使用不同的商店类型注册上下文

问题:不完全确定这是有效的,多个上下文变得混乱。

public void ConfigureServices(IServiceCollection services,  IHostingEnvironment env)
{
    var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNet5;Trusted_Connection=True;";

    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<BloggingContext>(options =>
        {
          if (env.IsEnviornment("test") { options.UseInMemoryStore(); }
          else { options.UseSqlServer(connection)); }
        });
 }

1 个答案:

答案 0 :(得分:0)

根据环境变量配置DbContext以使用不同的数据存储在技术上是有效的。我不明白为什么上面的示例代码不起作用。有关详细信息,请结帐Working with Multiple Environments

但我要注意,根据数据存储,EF的行为可能会有所不同。 EF7不会试图隐藏提供商之间的差异。例如,ALTER TABLE table1 DROP COLUMN col1适用于SQL Server,但在SQLite上失败。 EF7迁移目前不能弥补这一限制和其他限制。