0

I know this is repeated question and even here but I have tried all solutions without no sense. I have the main DB where the user check if found and return by his own or related database that should change the connection string to be current used one. My problem is that despite it's got the database correct but a dbcontext works on the main database it diverts again I don't why.

My applicationdbcontext is

public ApplicationDbContext(string connectionString)
           : base(string.IsNullOrEmpty(connectionString) ? "DefaultConnection" : connectionString, throwIfV1Schema: false)
{
    this.Database.CommandTimeout = 600;
}

public static ApplicationDbContext Create(string dbCatlogConn)
{
    return new ApplicationDbContext(ConString.dbCatlogConn);
}

and this is my public class

public class ConString
{
    public static string dbCatlogConn { get; set; }
}

This is my login in accountcontroller class

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl, string language = Config.DefaultLanguage)
{
    try
    {
        System.Web.Helpers.AntiForgery.Validate();
    }
    catch
    {
        return RedirectToRoute("Login", new { language, returnUrl });
    }

    dbName = model.username;

    Session["dbName"] = dbName;
    var dbname = db.SchoolLists
                   .Where(t => (t.dbname == dbName))
                   .Select(t => new { ConnString = t.ConnectionString }).ToList();

    // new conection
    dbConnectionString = "";
    Session["ConnectionString"] = dbConnectionString;
    db = new ApplicationDbContext();

    UserManager.PasswordHasher = new CustomPasswordHasher();

    bool CheckConnResult = db.Database.Exists();

    // code here
    var user = db.Users.Where(e => e.UserName.ToLower() == model.UserName.ToLower()).FirstOrDefault();
    var result = new SignInStatus();

    if (user == null)
        result = SignInStatus.Failure;
    else
    {
        string dbPassword = dal.DecryptPassword(user.AnotherUsername, user.AnotherSalt, user.PasswordHash);
        var status = UserManager.PasswordHasher.VerifyHashedPassword(dbPassword, model.Password);

        if (status == PasswordVerificationResult.Success)
            // error here
            result = await SignInManager.PasswordSignInAsync(model.UserName, user.PasswordHash, model.RememberMe, shouldLockout: false);
            // result = SignInStatus.Success;
        else
            result = SignInStatus.Failure;
    }

    switch (result)
    {
        case SignInStatus.Success:
                if (user != null)
                {
                    if (user.Disabled == true)
                    {
                        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                        ModelState.AddModelError("", language == "Invalid login attempt.");
                        // rest the connection to default
                        // = ConString.Mainbd;
                        return View(model);
                        //return View("Lockout");
                    }
                    else
                    {


                    }
                }

                return RedirectToLocal(returnUrl);

            case SignInStatus.LockedOut:
                return View("Lockout");

            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", language == "Invalid login attempt.");
                return View(model);
        }
}

I try also to change applicationdbcontext create in a startup file

app.CreatePerOwinContext(() => ApplicationDbContext.Create(ConString.dbCatlogConn));

but the ApplicationSignInManager always uses the main connection - it doesn't update for the new one after login despite I got the connection string correctly

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
mr.alaa
  • 76
  • 3
  • 11
  • Is there any solution suggested? – mr.alaa Nov 06 '19 at 05:28
  • Have you tried using multiple dbContexts ?https://stackoverflow.com/questions/21537558/multiple-db-contexts-in-the-same-db-and-application-in-ef-6-and-code-first-migra – aliassce Nov 07 '19 at 19:58
  • It is only change connection I think it is too simple but there is sometsomething which revert to the old connection – mr.alaa Nov 07 '19 at 22:25

1 Answers1

-1

Could you please try by creating a configure like below? and then change the connection string dynamically.

public static class ApplicationDbContextConfigurer
{
    public static void Configure(
        DbContextOptionsBuilder<ApplicationDbContext> builder, string connectionString)
    {
        builder.UseSqlServer(connectionString);
    }

    public static void Configure(
        DbContextOptionsBuilder<ApplicationDbContext> builder, DbConnection connection)
    {
        builder.UseSqlServer(connection);
    }
}

enter image description here

Change connection string

DbContextOptionsBuilder<ApplicationDbContext> builder = 
    new DbContextOptionsBuilder<VineforceDbContext>();

ApplicationDbContextConfigurer.Configure(builder, connectionString);
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Harsh Gupta
  • 307
  • 2
  • 14
  • @HarshGupta is it a new class and where I need to add it? – mr.alaa Nov 07 '19 at 16:23
  • @mr.alaa: yes, you can create a new class ApplicationDbContextConfigurer and a method in it configure. Whenever you want to change the connections string then you can call this method. just like as shown below. – Harsh Gupta Nov 08 '19 at 07:01
  • SignInManager still save the pervious connection after log out when it try to connect with anew database – mr.alaa Nov 08 '19 at 22:25