예제 #1
0
        /// <summary>
        ///     Switch tenant database.
        /// </summary>
        public void SwitchTenantDatabase()
        {
            //run in thread 'dbConnection.ConnectionString' is no pwd
            var dbConnection         = GetConnection();
            var mainConnectionString = TenantContext.GetMasterTenant();

            if (string.IsNullOrWhiteSpace(mainConnectionString))
            {
                mainConnectionString = string.IsNullOrWhiteSpace(ConnectionString)
                    ? dbConnection.ConnectionString
                    : ConnectionString;
                TenantContext.AddMasterTenant(mainConnectionString);
            }

            if (string.IsNullOrWhiteSpace(ConnectionString))
            {
                ConnectionString = mainConnectionString;
            }

            if (!TenantContext.IsTenant)
            {
                return;
            }

            var tenantName = TenantContext.CurrentTenant;

            if (string.IsNullOrWhiteSpace(tenantName))
            {
                return;
            }
            //Current tenant is main and connection string is not equal switch to main database
            if (tenantName.ToLower() == TenantContext.Master.ToLower())
            {
                if (mainConnectionString != dbConnection.ConnectionString)
                {
                    SwitchDatabase(dbConnection, mainConnectionString);
                }

                return;
            }

            //get tenant connection string
            var newConnectionString = TenantContext.GetCurrentTenant();

            if (string.IsNullOrWhiteSpace(newConnectionString))
            {
                newConnectionString = mainConnectionString.GetConnectionStringForTenant(tenantName);
                TenantContext.AddTenant(tenantName, newConnectionString);
            }

            SwitchDatabase(dbConnection, newConnectionString);
        }