c# - ASP.NET 5 多个 dbcontext 问题

标签 c# asp.net entity-framework asp.net-core entity-framework-core

我正在使用新的 ASP.NET 5 beta 8,当我有两个 dbcontext 时遇到了麻烦。

我有以下项目结构。

-Data(Identity 3 db with other entities)
-Resources (Contains a db with translations)
-WebApp 

剥离了 WebApp 中 Startup.cs 中的一些代码

 public void ConfigureServices(IServiceCollection services)
 {
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<DatabaseContext>(opt => opt.UseSqlServer(Configuration["Data:MainDb:ConnectionString"]));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<DatabaseContext>()
            .AddDefaultTokenProviders();

        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ResourceDbContext>(opt => opt.UseSqlServer(Configuration["Data:Resources:ConnectionString"]));

        services.AddTransient<IResourceDbContext, ResourceDbContext>();
        services.AddTransient<IDatabaseContext, DatabaseContext>();
}

在 ResourceDbContext 和 DatabaseContext 中,我执行以下操作

    public ResourceDbContext(DbContextOptions options) : base(options)
    {
        _connectionString = ((SqlServerOptionsExtension)options.Extensions.First()).ConnectionString;
    }


    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer(_connectionString);
    }

但是,当我从 appsettings.json 读取连接字符串时,我在 ConfigureServices 中收到了正确的值。但是 DbContextOptions 只包含最新加载的值,在本例中是资源的连接字符串。所以两个dbcontext都建立了到Resource db的连接。

我找不到关于此的任何信息。

最佳答案

您需要做的就是指明 DbContextOptions 是泛型类型:

public ResourceDbContext(DbContextOptions<ResourceDbContext> options) : base(options)
{

}

现在,依赖注入(inject)系统可以在创建 ResourceDbContext 并将其注入(inject)构造函数时找到正确的依赖项(DbContextOptions 选项)。

See implementation AddDbContext method


米罗斯拉夫·西斯卡:

public class GetHabitsIdentity: IdentityDbContext<GetHabitsUser, IdentityRole, string> where TUser : IdentityUser
{
    public GetHabitsIdentity(DbContextOptions<GetHabitsIdentity> options)
        :base(options)
    {

    }        
}

关于c# - ASP.NET 5 多个 dbcontext 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33532599/

相关文章:

c# - 如何在 aspx 页面的服务器脚本 block 中使用 [WebMethod]?

asp.net - 将 ASP.NET 应用程序服务配置为使用 'dbo' 以外的架构

entity-framework - 是否可以将现有的 MVC4 Web 应用程序升级到 MVC5?

c# - 是否可以订阅覆盖的基本事件?

c# - StringBuilder.Append with float

c# - 等待某事发生——异步或同步模型?

asp.net - 使用 Relay 和 graphql-dotnet 上传文件

sql-server - SQL Server 分区表和 Entity Framework

c# - 使用 MySQL 代替 LocalDb

c# - 当测试被赋予驱动程序类型作为测试用例时,如何实例化像 WebDriverWait 这样的变量?