asp.net mvc multitenant database per tenant

末鹿安然 提交于 2021-01-29 10:05:15

问题


I'm building an app for our company which needs to have separate database per client. App is for the usage of other multiple companies, so the app needs to identify the company name when the user logs in and make the users operate only within their company db. I have it all set, but the problem is that the app is not able to handle 2 different databases simultaneously. When users from two different companies log in, the first users db gets changed to the db of the second user who is logged in! This is of course unacceptable. How can I make the app to use 2 dbs simultaneously?

I have one database which collects all app users and their company names and separate databases for each company. I also have a standard asp below are my codes:

Login class and database initializer in account controller

        [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        bool ifDemo = false;
        string demoPrefix = "demo.";
        if (model.Email.StartsWith(demoPrefix))
        {
            ifDemo = true;
            model.Email = model.Email.Substring(demoPrefix.Length);
        }

        SetDatabaseInitializerAndInitializeIt(ifDemo, model.Email);


        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

        switch (result)
        {
            case SignInStatus.Success:
                returnUrl = CheckFirstLogin(model.Email, returnUrl);
                        await OnSignInSuccess(model);
                //FormsAuthentication.SetAuthCookie(model.Email, false);
                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("", "Invalid login attempt.");
                return View(model);
        }
    }

    public static void SetDatabaseInitializerAndInitializeIt(bool demoDB, string login)
    {
        Database.SetInitializer(new ApplicationUsersSeedData());
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<Facility.Data.FacilityEntities,
            Facility.Migrations.Configuration>());

        // Check current users company name and set the right database. 
        // To use demo version of database add "demo." prefix to the login email e.g: demo.testspamu79@gmail.com

        using (var domain = new Facility.Models.UserCommonDBContext())
        {
            domain.Database.Initialize(true);
        }

        UserCommonDBContext context = new Facility.Models.UserCommonDBContext();

        var companyName = context.CommonUser.Where(x => x.CommonUserEmail == login).FirstOrDefault().CommonUserCompanyName;
        if (demoDB)
            companyName = companyName + "Demo";

        using (var domain = new Facility.Data.FacilityEntities(companyName))
        {
            domain.Database.Initialize(true);
        }

    }

Dbcontext:

    public partial class FacilityEntities : DbContext
{
    public static string DbName;

    public FacilityEntities() : base(string.IsNullOrWhiteSpace(DbName) ? "Demo" : DbName)
    {
    }
    public FacilityEntities(string dbName) : base(dbName)
    {
        DbName = dbName;
    }

回答1:


as Tielson T. said in the comments, I got rid of static and stored db name in session, and now it works!



来源:https://stackoverflow.com/questions/50954745/asp-net-mvc-multitenant-database-per-tenant

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