Dynamic database connection using Asp.net MVC and Identity2

不羁岁月 提交于 2019-12-04 21:50:57

After hours spent in searching here my personal (maybe not the best) working solution.

In the Login action of AccountController, after the first check in "master" database, set the "specific" database informations in Session scope:

//Save the database infos in Session.
Session.Add("SqlServerInstance", masterUser.Company.DatabaseServer);
Session.Add("DbName", masterUser.Company.DatabaseName);

Always in AccountController update the SignInManager and UserManager properties fixing the connection string for the Identity context:

public ApplicationSignInManager SignInManager
    {
        get
        {
            //Set manually the right connection string used by the Identity database context.
            HttpContext.GetOwinContext().Get<ApplicationDbContext>().Database.Connection.ConnectionString = ApplicationDbContext.GetConnectionString();

            return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }
        private set
        {
            _signInManager = value;
        }
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            //Set manually the right connection string used by the Identity database context.
            HttpContext.GetOwinContext().Get<ApplicationDbContext>().Database.Connection.ConnectionString = ApplicationDbContext.GetConnectionString();

            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

And finally the method that give us the connection string:

/// <summary>
    /// Get the connection string getting SqlServerInstance and DbName from Session.
    /// </summary>
    public static string GetConnectionString()
    {

        string sqlServerInstance = DEFAULT_SQLSERVERINSTANCE;
        if (HttpContext.Current.Session != null && HttpContext.Current.Session["SqlServerInstance"] != null)
            sqlServerInstance = Convert.ToString(HttpContext.Current.Session["SqlServerInstance"]);

        string dbName = DEFAULT_DBNAME;
        if (HttpContext.Current.Session != null && HttpContext.Current.Session["DbName"] != null)
            dbName = Convert.ToString(HttpContext.Current.Session["DbName"]);

        return "Data Source=" + sqlServerInstance + ";Initial Catalog=" + dbName + ";Integrated Security=True";

    }

Hope this can help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!