public async Task <Tenant> AddTenant(Tenant tenant) { _db.Tenants.Add(tenant); await _db.SaveChangesAsync(); return(tenant); }
public async Task <IActionResult> CreateNewTenant(Tenant tenant) { try { if (tenant == null || string.IsNullOrWhiteSpace(tenant.Name) || string.IsNullOrWhiteSpace(tenant.ConnectionString)) { return(StatusCode((int)HttpStatusCode.UnprocessableEntity, "The tenant name and connection string must not be null")); } var tenantName = tenant.Name; var connectionString = Regex.Unescape(tenant.ConnectionString); var connectionStringBuilder = new SqlConnectionStringBuilder(connectionString); if (_tenantsDbContext.Tenants.Any(tenant => tenant.Name == tenantName)) { return(StatusCode((int)HttpStatusCode.InternalServerError, $"The tenant: {tenantName}. Is already in the tenants database.")); } var newTenant = new Tenant { Guid = Guid.NewGuid().ToString(), Name = tenantName, ConnectionString = connectionStringBuilder.ConnectionString }; _tenantsDbContext.Tenants.Add(newTenant); await _tenantsDbContext.SaveChangesAsync(); var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>(); var options = optionsBuilder.UseSqlServer(connectionStringBuilder.ConnectionString).Options; var dbContext = new ApplicationDbContext(options); dbContext.Database.Migrate(); //Data.SeedData.Seed(dbContext); if (TenantsCustomFolderManager.CreateContentDirectoryIfItDoesNotExist(_tenantsDirectory, tenantName)) { _logger.LogInformation($"Custom content folder created for: {tenantName}"); } TenantsCustomFolderManager.CreateTenantInConfiguration(tenantName, connectionStringBuilder.ConnectionString); return(Ok("Tenant Created")); } catch (Exception ex) { _logger.LogError(ex.Message); return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message)); } }