I need to run-time change the dbContext
for Request.GetOwinContext()
to use a specific connectionString
but it's not working.
I've a dbContex
class
to accept a default connectionString
from Web.Config
or a specified one like this:
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;
}
}
then when a new user is registering i've tried to change the Owin's default dbContext for one with a new connectionString like this:
[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);
(...)
}
until and including appDbContext
everything works as expected but on debuging, after setting context.Set<ApplicationDbContext>...
the context
is still using the default one.
I've also tried using var context = Request.GetOwinContext();
and setting directly as HttpContext.Current.GetOwinContext().Set<ApplicationDbContext>("ApplicationDbContext", appDbContext);
and Request.GetOwinContext().Set<ApplicationDbContext>("ApplicationDbContext", appDbContext);
but I always get the same result.