【问题标题】:change OwinContext dbContext on runtime在运行时更改 OwinContext dbContext
【发布时间】: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&lt;ApplicationDbContext&gt;...context 仍使用默认设置。

我也尝试过使用var context = Request.GetOwinContext(); 并直接设置为HttpContext.Current.GetOwinContext().Set&lt;ApplicationDbContext&gt;("ApplicationDbContext", appDbContext);Request.GetOwinContext().Set&lt;ApplicationDbContext&gt;("ApplicationDbContext", appDbContext);,但我总是得到相同的结果。

【问题讨论】:

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


    【解决方案1】:

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

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

    必须改为

    context.Set<ApplicationDbContext>(appDbContext);
    

    【讨论】:

    • 我相信这是因为.Set&lt;T&gt; 是弱类型方法?
    • 您好,我也做了同样的事情,但用户管理器仍在使用旧的 dbcontext..您可以在这里帮忙:stackoverflow.com/questions/45315809/…
    猜你喜欢
    • 2012-09-04
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2011-04-10
    • 2011-01-01
    • 2010-12-05
    相关资源
    最近更新 更多