Шаблон Nano ASP.NET для SaaS
Учетные данные администратора (для всех арендаторов): admin@email.com / Password123!
Пример данных обнуляется каждый час
Контакты

Build a Multi-Tenant App With Multiple Databases – Free Guide (Part 2)

Райан Льюис
Сентябрь 13, 2023

In the last article, we learned the basics of building a multi-tenant application with ASP.NET и Entity Framework. In this article, we will build on that same project and refactor the solution to use a per-tenant database approach.

If you haven’t read the previous article on Building Multi-Tenant Applications with Entity Framework and ASP.NET, please check that out here. If you don’t already have it, download the finished GitHub project of that article because that will serve as the starting point for this article.

Download the finished version of Part 1: Single-Database Multi-Tenant App here from GitHub

The completed version of the multi-tenant solution we will build in this article is also available as a finished GitHub repository.

Download the finished version of this tutorial Part 2: Multiple-Database Multi-Tenant App here from GitHub

Download the Postman collection for testing здесь.

To support multiple databases, we will need to make a few critical changes:

  • Save a connection string per each tenant
  • Add an OnConfiguring method to our database context model to allow for using a different connection string per each request.
  • Add a tenant service & controller to allow creating new tenants
  • Run migrations when creating a new tenant
  • During startup, run any pending migrations on tenant databases

To begin, let’s start by adding a new string field to the Арендатор table and call it ConnectionString. This is where we will specify the connection string for the tenant-specific database or choose to leave null and have the tenant use the default shared database. Make sure to allow null values on the ConnectionString property by adding a question mark.

общедоступный класс Арендатор
{
    [Ключ]
    [Сгенерировано из базы данных(Параметр, сгенерированный базой данных.Нет)]
    общедоступный строка Идентификатор { get; набор; }
    общедоступный строка Имя { get; набор; }
    общедоступный строка? ConnectionString { get; набор; }

}

Next we should update our CurrentTenantService class and interface to include this new ConnectionString field so that the ConnectionString property is always available.

В SetTenant method, we will retrieve the connection string from the database and set the property at the same time that we set the tenant Идентификатор.

With that out of the way, we’ll update the ApplicationDbContext class to use the connection string when there is one in its О настройке override method, which fires on every request.

In the last tutorial, we added two key overrides в ApplicationDBContext to get our multi-tenant application working. The first was the OnModelCreating override where we added a query filter to select only those records which had matching a tenant Id. The second was the Сохранить изменения override where we saved the current tenant Id to any entity that implemented the IMustHaveTenant interface.

We will now add a third override to tell entity framework to use a different connection string whenever there’s one specified by the current tenant. The override we will add is the О настройке method, which fires on every request.

 общедоступный класс ApplicationDbContext : DbContext
 {
     частный только для чтения ICurrentTenantService _currentTenantService;
     общедоступный строка Идентификатор текущего арендатора { get; набор; }
     общедоступный строка Строка подключения текущего арендатора { get; набор; }


     // Конструктор 
     общедоступный ApplicationDbContext(ICurrentTenantService currentTenantService, DbContextOptions<ApplicationDbContext> варианты) : база(варианты)
     {
         _currentTenantService = currentTenantService;
         Идентификатор текущего арендатора = _currentTenantService.Идентификатор арендатора;
         Строка подключения текущего арендатора = _currentTenantService.ConnectionString;

     }

     // Наборы баз данных приложения (DbSets) — создаются для типов сущностей и применяются ко всем базам данных
     общедоступный DbSet<Продукт> Продукция { get; набор; }

     // При создании модели — фильтр запросов для многопользовательской среды, срабатывает один раз при запуске приложения
     защищенный переопределить void OnModelCreating(Конструктор ModelBuilder)
     {         
         строитель.Объект<Продукт>().HasQueryFilter(a => a.Идентификатор арендатора == Идентификатор текущего арендатора); 
     }

     // При настройке — динамическая строка подключения, запускается при каждом запросе
     защищенный переопределить void О настройке(DbContextOptionsBuilder optionsBuilder)
     {
         строка tenantConnectionString = Строка подключения текущего арендатора;
         если (!строка.IsNullOrEmpty(tenantConnectionString)) // использовать базу данных арендатора, если она указана
         {
             _ = optionsBuilder.UseSqlServer(tenantConnectionString);
         }
     }
     
     // При сохранении изменений — записать идентификатор арендатора в таблицу
     общедоступный переопределить int Сохранить изменения()
     {        
         foreach (var запись в ChangeTracker.Записи<IMustHaveTenant>().ToList()) 
         {
             переключатель (запись.Штат)
             {
                 случай Состояние объекта.Добавлено:
                 случай Состояние объекта.Изменено:
                     запись.Объект.Идентификатор арендатора = Идентификатор текущего арендатора; 
                     перерыв;
             }
         }
         var результат = база.Сохранить изменения();
         возврат результат;
     }
 }

The code in the О настройке override checks for any tenant specific connection string for the current tenant and when there is one, passes that connection string as an option optionsBuilder. Doing this will tell entity framework to use this connection string for the current request. If the current tenant connection string is null, the optionsBuilder code isn’t triggered and the request will use the default connection string like it normally would.

In a multiple database setup, we need to consider that there are two types of databases. One being the main ‘central’ shared database that stores the tenant table itself, along with any other configuration-related tables that we may add in the future like subscription, billing, or even identity. And then there are all the other databases, which are per-tenant and should not contain those central configuration tables. The tenant-specific databases should only contain application-related tables, like Продукция and any more that we add.

To achieve this, we will need manage two sets of migrations: one set for entities that are exclusive to the central database, and another set for all the other tables which can be found across all the databases.

Let’s begin by removing the миграции and database snapshot we created in the previous tutorial (there should only be one called initial).  We should also remove the Tenants DbSet from the ApplicationDbContext because we don’t want that table to be generated in the tenant-specific databases.

If we were being strict about every tenant having their own database, we could actually remove the tenant query filters and tenant ID columns. Its better to leave it though because it will allow for tenants to share the same database and still retain data isolation. This is what you would call a гибридный multi-tenant implementation.

In our single-database multi-tenant setup, we used the TenantDbContext purely for looking up tenant information when a request comes in. It was essentially a read-only context and had no responsibilities in terms of migrations. In this multi-database setup, we’ll still be using it as a lookup context for incoming request, but we’ll also use it to manage migrations on tables specific to the main central database.  The ApplicationDbContext will manage migrations on tables found across every tenant database.

Откройте Консоль диспетчера пакетов and create an initial migration for the central database. For that we will need to target the TenantDbContext. To keep things organized, we can also specify an output directory for migrations to keep the two groups separate with the -o switch. Here is the command:

add-migration Initial -context TenantDbContext -o Migrations/TenantDb

Lets apply the migration by typing the following:

update-database -context TenantDbContext 

Now if we go explore our databases, can see that one was created and it contains one table for tenants. If we expand the migrations folder in the solution explorer, we should see there is a new subfolder called TenantDb and that contains our migration. If that’s the case for you, then you’ve done everything correctly up to this point.

Next, we’ll create another migration this time for the ApplicationDbContext. Back in Консоль диспетчера пакетов type the following command, this time notice we specify a new context and a new output directory:

add-migration InitialApp -context ApplicationDbContext -o Migrations/AppDb

Let’s apply the migration by typing the following:

update-database -context ApplicationDbContext 

If we check the database now, we’ll see that the products table has been created. In the solution explorer, there is another folder in migrations with the new migration we just added.

В single-database setup from the previous tutorial, we never actually made a service or controller to handle creation of new tenants. In that simplistic setup, we just added the tenants manually in the table itself. With a multiple database setup however, that will not suffice because we will need to run some automation when we create new tenants. Every time a new tenant is created, we’ll need to generate a connection string, spin up a new database, and apply any pending migrations.

Start by creating a new folder in Услуги называемый TenantService and add an interface called ITenantService. In this interface define one method called CreateTenant. In a real application, there should be methods for retrieving lists, and updating tenants. For brevity, we will only worry about creating tenants in this tutorial.

общедоступный интерфейс ITenantService
{
    Арендатор CreateTenant(Запрос CreateTenantRequest);
}

Create a new DTO folder within the TenantService folder and call it CreateTenantRequest. It will contain an Идентификатор и Имя property like the Арендатор entity itself and also a Boolean field called Изолированный to indicate if this tenant should have its own isolated database.

общедоступный класс CreateTenantRequest
{
    общедоступный строка Идентификатор { get; набор; }
    общедоступный строка Имя { get; набор; }
    общедоступный bool Изолированный { get; набор; }
}

Finally let’s create the service itself, called TenantService.

общедоступный класс TenantService : ITenantService
{

    частный только для чтения TenantDbContext _context; // контекст базы данных
    частный только для чтения IConfiguration _configuration;
    частный только для чтения IServiceProvider _serviceProvider;

    общедоступный TenantService(TenantDbContext context, IConfiguration configuration, IServiceProvider serviceProvider)
    {
        _контекст = контекст;
        _configuration = configuration;
        _serviceProvider = serviceProvider;
    }

    общедоступный Арендатор CreateTenant(Запрос CreateTenantRequest)
    {

        строка newConnectionString = null;
        если (запрос.Изолированный == верно)
        {
            // generate a connection string for new tenant database
            строка dbName = "multiTenantAppDb-" + запрос.Идентификатор;
            строка defaultConnectionString = _configuration.GetConnectionString("Подключение по умолчанию");
            newConnectionString = defaultConnectionString.Replace("multiTenantAppDb", dbName);

            // create a new tenant database and bring current with any pending migrations from ApplicationDbContext
            попробуйте
            {
                с использованием IServiceScope scopeTenant = _serviceProvider.CreateScope();
                ApplicationDbContext dbContext =   scopeTenant.ServiceProvider.GetRequiredService<ApplicationDbContext>();
                dbContext.Database.SetConnectionString(newConnectionString);
                если (dbContext.Database.GetPendingMigrations().Any())
                {
                    Консоль.ForegroundColor = ConsoleColor.Blue;
                    Консоль.WriteLine("$»Applying ApplicationDB Migrations for New '{запрос.Идентификатор}' tenant.");
                    Консоль.ResetColor();
                    dbContext.Database.Migrate();
                }
            }
            поймать (Исключение ex)
            {
                бросить новый Исключение(например.Сообщение);
            }
        }


        Tenant tenant = новый() // create a new tenant entity
        {
            Идентификатор = запрос.Идентификатор,
            Имя = запрос.Имя,
            ConnectionString = newConnectionString,
        };

        _контекст.Добавить(арендатор);
        _контекст.Сохранить изменения();

        возврат арендатор;
    }
}

In this service, we’ll use the TenantDbContext to interact with tenant data since its data that is managed only in the central database. The CreateTenant method takes the DTO as a request and in the case of an isolated tenant, performs several additional steps.

The first step is to generate a new connection string. We could just hard code a base connection string, but a slightly more elegant solution is to use the IConfiguration interface, which allows us to read fields from appsettings.json. We read the Подключение по умолчанию из appsettings.json and simply add a dash with the Идентификатор of the tenant to the central database name. In a real application, you might want to ensure that no whitespace or illegal characters are present in the Идентификатор of the tenant before proceeding further.

The next step is critical. Using the help of the IServiceProvider interface, we pull down a new scoped instance of the ApplicationDbContext from the service provider. With this instance, we set the new connection string on it and then check for any pending migrations. Of course there will be pending migrations because there isn’t even a database created yet. The framework will detect that and apply all pending ApplicationDbContext migrations.

Isolated database or not, the final step of the create tenant method is to save the new Tenant to the main database.

Lastly, in Program.cs we’ll need to add the Tenant service to the service container as a transient service so it can be used throughout our application. Add the following line after the product service we created in the previous tutorial.

строитель.Услуги.AddTransient<ITenantService, TenantService>();

To make use of the new tenant service and interact with it via REST API calls, create a new API controller в Контроллеры folder called TenantsController. We’ll inject the tenantService in the constructor and use it in the Post method as follows:

[Маршрут("api/[контроллер]")]
[ApiController]
общедоступный класс TenantsController : ControllerBase
{
    частный только для чтения ITenantService _tenantService;

    общедоступный TenantsController(ITenantService tenantService)
    {
        _tenantService = tenantService;
    }

    общедоступный ITenantService TenantService { get; }

    // Create a new tenant
    [HttpPost]
    общедоступный IActionResult Сообщение(Запрос CreateTenantRequest)
    {
        var результат = _tenantService.CreateTenant(запрос);
        возврат Хорошо(результат);
    }
}

With that out of the way, run the application and we can open up Postman to test everything out.

Make a new Сообщение API call with the following JSON in the body. The Имя of the tenant can be however you want but the Идентификатор cannot contain any special characters or whitespace. The Идентификатор remember is what will be appended to the database name to create the new tenant-specific database. Set the Изолированный boolean to верно so that a new database is created when you send the request.

Here is a postman collection you can use to make your life easier.

Once you click send, you should receive a 200 OK status response and a new database should appear when you refresh your database explorer! Create a few more tenants both isolated and shared to see what happens.

The query filters and dynamic connection string should be working too. Try creating some sample products to see what happens. Remember to change the tenant ID in the header when sending requests. New products will be saved to their tenant databases when a connection string is specified. Now obviously this is in no way secure since anyone can just change the request header and access another tenant. To secure the application you would need to integrate ASP Identity and store/read the tenant key in a token. The Nano ASP.NET Boilerplate has that all taken care of already along with a lot of other great features and will definitely save you a lot of time messing with that.

Alas we have multi-tenant behavior implemented in a per-tenant database model! But we can’t call it a day just yet. We need to consider what happens when we create new migrations. If we add a new field to Product and run a migration, that migration won’t be applied to all the tenant databases, only the central one. That is a problem that we will address in the following section.

Running the обновить базу данных command will apply migrations on only the one database specified in the default connection string found in appsettings.json. What we need is to loop through each tenant, and apply migrations for every database found – not just the main one. Luckily, there is a way to programmatically apply migrations instead of having to type the command into PMC using the .migrate() method. We’ll rely on this method to achieve the goal.

In summary what we need to do is:

  • Tap into the app startup process using a service extension
  • Apply any migrations to the main database (TenantDbContext)
  • Read the Tenant table
  • Loop through each tenant
  • When a tenant has a connection string, apply any ApplicationDbContext migrations for this database instance

Start by creating a new folder in the solution explorer called Расширения. What we are creating here is an extension method to the app configuration process. I’ve named this static class MultipleDatabaseExtensions and it has one method AddAndMigrateTenantDatabases. The code is as follows:

общедоступный static класс MultipleDatabaseExtensions
{
    общедоступный static IServiceCollection AddAndMigrateTenantDatabases(this IServiceCollection services,   IConfiguration configuration)
    {

        // Tenant Db Context (reference context) - get a list of tenants
        с использованием IServiceScope scopeTenant = services.BuildServiceProvider().CreateScope();
        TenantDbContext tenantDbContext = scopeTenant.ServiceProvider.GetRequiredService<TenantDbContext>();

        если (tenantDbContext.Database.GetPendingMigrations().Any())
        {
            Консоль.ForegroundColor = ConsoleColor.Blue;
            Консоль.WriteLine("Applying BaseDb Migrations.");
            Консоль.ResetColor();
            tenantDbContext.Database.Migrate(); // apply migrations on baseDbContext
        }


        Список<Арендатор> tenantsInDb = tenantDbContext.Арендаторы.ToList();

        строка defaultConnectionString = configuration.GetConnectionString("Подключение по умолчанию"); // read default connection string from appsettings.json

        foreach (Tenant tenant в tenantsInDb) // loop through all tenants, apply migrations on applicationDbContext
        {
            строка connectionString = строка.IsNullOrEmpty(арендатор.ConnectionString) ? defaultConnectionString : арендатор.ConnectionString;

            // Application Db Context (app - per tenant)
            с использованием IServiceScope scopeApplication = services.BuildServiceProvider().CreateScope();
            ApplicationDbContext dbContext = scopeApplication.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            dbContext.Database.SetConnectionString(connectionString);
            если (dbContext.Database.GetPendingMigrations().Any())
            {
                Консоль.ForegroundColor = ConsoleColor.Blue;
                Консоль.WriteLine("$»Applying Migrations for '{арендатор.Идентификатор}' tenant.");
                Консоль.ResetColor();
                dbContext.Database.Migrate();
            }
        }

        возврат services;
    }

}

This class is going to take care of migrations for both contexts, TenantDbContext и ApplicationDbContext. First it will create a scoped instance of the TenantDbContext on the main database. We know it’s the main database because we aren’t specifying any connection string options and it will therefore use the default one. If there any TenantDbContext migrations pending, they will get applied.

Next, we read a list of Tenants using this same context instance. We loop through each tenant in the list and if there is a connection string present, we use it. Otherwise, in a case of null, we set the connection string to the default database. Any pending ApplicationDbContext migrations are then applied to the target database instance.

Finally, we need to hook this into the app configuration process back in program.cs. Right after the code that adds database contexts, add this line. Now this extension will run whenever the app starts.

строитель.Услуги.AddAndMigrateTenantDatabases(строитель.Настройка);

This is how the Program.cs class should look at this point

с использованием Microsoft.EntityFrameworkCore;
с использованием multiTenantApp.Расширения;
с использованием multiTenantApp.Middleware;
с использованием multiTenantApp.Модели;
с использованием multiTenantApp.Услуги;
с использованием multiTenantApp.Услуги.Продукты и услуги;
с использованием multiTenantApp.Услуги.TenantService;

var строитель = Веб-приложение.CreateBuilder(args);

// Add services to the container.
строитель.Услуги.Добавить контроллеры();
строитель.Услуги.AddEndpointsApiExplorer();

// Current tenant service with scoped lifetime (created per each request)
строитель.Услуги.AddScoped<ICurrentTenantService, CurrentTenantService>();

// добавление службы базы данных с конфигурацией — строка подключения считывается из файла appsettings.json
строитель.Услуги.AddDbContext<ApplicationDbContext>(варианты => варианты.UseSqlServer(строитель.Настройка.GetConnectionString("Подключение по умолчанию")));
строитель.Услуги.AddDbContext<TenantDbContext>(варианты => варианты.UseSqlServer(строитель.Настройка.GetConnectionString("Подключение по умолчанию")));
строитель.Услуги.AddAndMigrateTenantDatabases(строитель.Настройка);

// Product CRUD service with transient lifetime
строитель.Услуги.AddTransient<ITenantService, TenantService>();
строитель.Услуги.AddTransient<IProductService, Продукты и услуги>();

var приложение = строитель.Создать();

приложение.Использование перенаправления по HTTPS();
приложение.Разрешение на использование();
приложение.UseMiddleware<TenantResolver>();
приложение.MapControllers();

приложение.Запустить();

To test out our new extension, create a new string field in the Продукция table called Supplier. Generate a new migration with the following command, remember to specify the контекст и output folder. Since Продукт is an application table found in every database, we will use the ApplicationDbContext:

add-migration AddFieldToProduct -context ApplicationDbContext -o Migrations/AppDb

Now that our migrations are handled programmatically, all we need to do is run the application. There’s no need to run the обновить базу данных command. If you do run the обновить базу данных command, you will get a message saying that no migrations were applied. This is because before Entity Framework applies the migrations, it builds the application. During that build process, our application applies the pending migrations. As a result, by the time the command runs, no migrations are pending.

Run the app and inspect the databases. You will see that the new field has been added to our main database and all of the tenant databases as well. We now have a completely functional multiple database multi-tenant setup.

Any migrations on both the TenantDbContext и ApplicationDbContext will be handled programmatically by this new extension method.

We may find ourselves feeling like Ripley from the original Alien film now, having nuked the USCSS Nostromo and thinking our problems are behind us. But suddenly the alien crawls out of the wall for one final fight. And here is that scene for us:

There is one last issue and that is that you will get an error if you try to add any fields to the Арендатор table. Strangely, adding new entities to the TenantDbContext or modifying any of those entities wont result in any problem. Only the Арендатор table will give you an error. Try adding a new field to the Tenant entity called SubscriptionLevel and create a new migration. Remember to specify the TenantDbContext and the output directory:

add-migration AddFieldToTenant -context TenantDbContext -o Migrations/TenantDb

Now run the app to apply the migration. This is the error you will receive

This, as you could image, took hours to figure out just what in the actual F&#! was going on when I first encountered the issue.

The problem is in our AddAndMigrateTenantDatabases method, where we read a list of Арендаторы from the Tenants table. We cannot read from a table that is being modified during design time. Well, we can but we need to tell the Entity Framework scaffolding tool explicitly which connection string we want to use in design time.

Entity Framework Core provides an interface we can use to specify criteria we want to use which will override and default behavior during design time. That interface is aptly named IDesignTimeDbContextFactory and it takes the DbContext in question as a type. Create a new class in the Модели folder called TenantDbContextFactory and follow the code example below:

общедоступный класс TenantDbContextFactory : IDesignTimeDbContextFactory<TenantDbContext>
{
    общедоступный TenantDbContext CreateDbContext(строка[] args) // neccessary for EF migration designer to run on this context
    {

        // Build the configuration by reading from the appsettings.json file (requires Microsoft.Extensions.Configuration.Json Nuget Package)
        IConfigurationRoot configuration = новый ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Создать();

        // Retrieve the connection string from the configuration
        строка connectionString = configuration.GetConnectionString("Подключение по умолчанию");


        DbContextOptionsBuilder<TenantDbContext> optionsBuilder = новый();
        _ = optionsBuilder.UseSqlServer(connectionString);
        возврат новый TenantDbContext(optionsBuilder.Options);
    }
}

The critical line of code is the DbContextOptionsBuilder<TenantDbContext> part near the end where we specify the connection string. The rest of the code is just making things clean by reading the default connection string from appsettings.json to avoid hard coding it in this class. To read from configuration in this class you will need to install one Nuget package, Microsoft.Extensions.Configuration.Json.

With that class added, run the app to apply the new migration. The app should start without issue and the new field will be added to the tenant table.

Well, that was fun, wasn’t it? Now you can tell all your friends you know how to create a multi-tenant application with a database per tenant implementation and they will no doubt think that that’s awesome. They may even proceed to tell you about their new app idea and ask you to build it for them.

There are a few things to consider before embarking down the database per tenant path. One is that this setup is only complete on our local development environment. You would need to add additional code to handle creating new databases on your cloud provider’s infrastructure. Cloud providers like Azure and AWS provide .NET SDKs for this very thing.

The other concern is that managing migrations can be difficult in situations where things go wrong. Imagine a scenario though where you have 50 tenant databases and for some reason one of them throws an error. Reverting to a previous state or doing any kind of backtracking is notoriously difficult. You should plan for these kinds of issues before deciding to run multiple databases.

Consider all the pros and cons of a multiple database setup before choosing it. A multi-database setup may be more efficient when it comes to scaling but single database multi-tenant setups are much easier to manage in regards to deployment and migrations.

If you are planning to build an MVP and are looking for it to scale and have robust SaaS features, consider using the Nano ASP.NET Boilerplate. You’ll yourself a lot of time getting your project off the ground.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

3 comments on “Build a Multi-Tenant App With Multiple Databases – Free Guide (Part 2)”

  1. Ntsikelelo:

    This was amazing! I am new to the world of multi-tenancy, could not have wished for a better intro.

  2. John Holliday:

    Execellent read. I’m using the .NET 8.0 version which has similar functionality, but does not map to the code you reference in this article. It would be great to have an updated version that matches the code.

  3. Michel:

    This post help me a lot. Thanks for sharing.

Вам нужен шаблон ASP.NET для создания вашего следующего MVP?
Ознакомьтесь с шаблоном проекта Nano ASP.NET для многопользовательского SaaS и сэкономьте недели или месяцы времени на разработке.
Узнать больше