Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change OwinContext dbContext on runtime

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.

like image 367
FabioG Avatar asked Dec 12 '25 13:12

FabioG


1 Answers

the problem here was the first string I was trying to use when setting, so this line

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

must be changed to

context.Set<ApplicationDbContext>(appDbContext);
like image 101
FabioG Avatar answered Dec 14 '25 03:12

FabioG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!