在运行时更改OwinContext dbContext

时间:2015-09-30 11:06:03

标签: c# asp.net-identity owin dbcontext

我需要在运行时更改dbContext的{​​{1}}以使用特定的Request.GetOwinContext(),但它无效。

我有connectionString dbContex来接受来自class的默认connectionString或指定的默认Web.Config

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);,但我总是得到相同的结果。

1 个答案:

答案 0 :(得分:1)

这里的问题是我在设置时尝试使用的第一个字符串,所以这一行

context.Set<ApplicationDbContext>("ApplicationDbContext", appDbContext);

必须更改为

context.Set<ApplicationDbContext>(appDbContext);