每个租户的asp.net mvc多租户数据库

时间:2018-06-20 18:21:15

标签: asp.net asp.net-mvc entity-framework multi-tenant dbcontext

我正在为我们的公司构建一个应用程序,该应用程序需要每个客户端有单独的数据库。该应用程序供其他多个公司使用,因此该应用程序需要在用户登录时标识公司名称,并使用户仅在其公司数据库内操作。 我已经设置好了,但是问题是该应用程序无法同时处理2个不同的数据库。当来自两个不同公司的用户登录时,第一个用户的数据库将更改为已登录的第二个用户的数据库!这当然是不可接受的。如何使应用程序同时使用2个数据库?

我有一个数据库,该数据库收集所有应用程序用户及其公司名称,以及每个公司的单独数据库。我也有一个标准的ASP 以下是我的代码:

帐户控制器中的登录类和数据库初始化程序

        [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 个答案:

答案 0 :(得分:0)

正如Tielson T.在评论中所说,我摆脱了静态并在会话中存储了数据库名称,现在它可以工作了!