0

I want to change my connectionstring at runtime based on the code user enters at login screen. I did the following

ApplicationDbContext

 public static ApplicationDbContext Create(string scCode){
        return new ApplicationDbContext("name=GEContext_" + scCode);
    } 

And at login i change the connectionstring as follows

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);
 ....
   }
 }
}

Now it is still referring to the original database...what am i missing?

P.S. For a history/detail consider this post

Samra
  • 1,815
  • 4
  • 35
  • 71

1 Answers1

0

Hi I Got the Answer from here

The problem was in ApplicationDbContext where we need to specify a default database whereas in my scenario that default database had to change. So i changed it using

 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>();
Samra
  • 1,815
  • 4
  • 35
  • 71