问题描述
我的新ASP.NET 5测试版8玩耍,并有麻烦的时候,我有两个的DbContext。
I'm playing around with the new ASP.NET 5 beta 8 and having trouble when I have two dbcontext.
我有以下的项目结构。
I have the following project structure.
-Data(Identity 3 db with other entities)
-Resources (Contains a db with translations)
-WebApp
剥夺一些code在Startup.cs在Web应用程序
Stripped away some code in Startup.cs in WebApp
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我做以下
In both ResourceDbContext and DatabaseContext I do the following
public ResourceDbContext(DbContextOptions options) : base(options)
{
_connectionString = ((SqlServerOptionsExtension)options.Extensions.First()).ConnectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(_connectionString);
}
然而,当我从appsettings.json阅读我的ConnectionStrings我收到ConfigureServices正确的价值观。但DbContextOptions仅包含最新加载的值,在这种情况下,对于资源的ConnectionString。所以,这两个的DbContext建立与资源数据库的连接。
However when I read my connectionstrings from appsettings.json I receive the correct values in ConfigureServices. But the DbContextOptions only contains the latest loaded value, in this case the connectionstring for Resources. So both dbcontext establishes a connection to Resource db.
我无法找到有关此的任何信息。
I'm unable to find any information about this.
推荐答案
所有你需要做的是表明DbContextOptions是一个泛型类型:
All you need to do is indicate that DbContextOptions is a generic type:
public ResourceDbContext(DbContextOptions<ResourceDbContext> options) : base(options)
{
}
现在依赖注入系统能够找到合适的依赖( DbContextOptions选项
),目前它创建ResourceDbContext并将其注入到构造。
Now the dependency injection system can find the right dependency (DbContextOptions options
) at the moment it creates ResourceDbContext and injects it into the constructor.
见实施AddDbContext方法
有关米罗斯拉夫Siska:
For Miroslav Siska:
public class GetHabitsIdentity: IdentityDbContext<GetHabitsUser, IdentityRole, string> where TUser : IdentityUser
{
public GetHabitsIdentity(DbContextOptions<GetHabitsIdentity> options)
:base(options)
{
}
}
这篇关于ASP.NET 5多的DbContext问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!