我正在使用新的 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/