我想根据用户在登录屏幕上输入的代码在运行时更改我的连接字符串。我做了以下工作
ApplicationDbContext
public static ApplicationDbContext Create(string scCode){
return new ApplicationDbContext("name=GEContext_" + scCode);
}
登录时,我更改连接字符串如下
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
try
{
System.Web.HttpContext.Current.Session["SchoolCode"] = model.SchoolCode;
var appDbContext = ApplicationDbContext.Create(model.SchoolCode);
HttpContext.GetOwinContext().Set<ApplicationDbContext>(appDbContext);
....
}
}
}
现在它仍然指的是原始数据库...我错过了什么?
附言有关历史/详细信息,请考虑这篇文章
嗨,我从这里得到了答案
问题出在 ApplicationDbContext 中,我们需要指定一个默认数据库,而在我的方案中,默认数据库必须更改。 所以我用
var appDbContext = ApplicationDbContext.Create(System.Web.HttpContext.Current.Session["SchoolCode"].ToString());//new ApplicationDbContext("name=GEContext", System.Web.HttpContext.Current.Session["SchoolCode"].ToString());
HttpContext.GetOwinContext().Set<ApplicationDbContext>(appDbContext);
HttpContext.GetOwinContext().Set<ApplicationUserManager>(new ApplicationUserManager(new UserStore<ApplicationUser, Role, int, UserLogin, UserRole, UserClaim>(appDbContext)));
return HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();