【发布时间】:2015-12-28 03:30:29
【问题描述】:
我需要在运行时将dbContext 更改为Request.GetOwinContext() 以使用特定的connectionString,但它不起作用。
我有一个dbContex class 可以接受来自Web.Config 的默认connectionString 或像这样指定的connectionString:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("AuthEntities", throwIfV1Schema: false)
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
public ApplicationDbContext(string sConnectionString)
: base(sConnectionString, throwIfV1Schema: false)
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public static ApplicationDbContext Create(string sConnectionString)
{
ApplicationDbContext test = new ApplicationDbContext(sConnectionString);
return test;
}
}
然后,当新用户注册时,我尝试使用新的 connectionString 更改 Owin 的默认 dbContext,如下所示:
[AllowAnonymous]
[Route("create")]
public async Task<IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel)
{
(...)
//get the specific connectionString
var connectionString = cService.GetCompanyConnectionString(createUserModel.Company);
//generate new dbContext
var appDbContext = ApplicationDbContext.Create(connectionString);
//get OwinContext
var context = HttpContext.Current.GetOwinContext();
//replace the DbContext inside OwinContext
context.Set<ApplicationDbContext>("ApplicationDbContext", appDbContext);
(...)
}
直到并包括appDbContext 一切都按预期工作,但在调试时,设置context.Set<ApplicationDbContext>... 后context 仍使用默认设置。
我也尝试过使用var context = Request.GetOwinContext(); 并直接设置为HttpContext.Current.GetOwinContext().Set<ApplicationDbContext>("ApplicationDbContext", appDbContext); 和Request.GetOwinContext().Set<ApplicationDbContext>("ApplicationDbContext", appDbContext);,但我总是得到相同的结果。
【问题讨论】:
标签: c# asp.net-identity owin dbcontext