3

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.

FabioG
  • 2,936
  • 3
  • 31
  • 50

1 Answers1

1

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);
FabioG
  • 2,936
  • 3
  • 31
  • 50
  • I believe this is because `.Set` is a Weakly Typed method? – Chef_Code Mar 25 '16 at 21:10
  • Hi i have done the same but the usermanager is still using old dbcontext..can u help here: https://stackoverflow.com/questions/45315809/how-to-change-database-name-in-dbcontext-connection-string-at-runtime – Samra Jul 27 '17 at 02:53