简体   繁体   中英

Entity Framework Core migrations on multiple databases

I am creating a .NET 6 API using EF core with SQL Server, and trying to implement multiple databases that would different connection strings based on an id that is passed in from an identity token. Essentially, there would be multiple databases that each contain the same tables, but storing different information. A user would be able to edit data from the front end and based on the "tenant" that they are working in, it would store the data in the appropriate database. For the time being, all of the databases will be on the same server.

When a user makes a request, I have been able to implement that correctly, using the following inside of my DbContext:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if(!optionsBuilder.IsConfigured)
            {
                var tenantId = _httpContext.GetClaim("tenantId");
                optionsBuilder.UseSqlServer(GetClientConnectionString(tenantId));
            }
        }

where the GetClientConnectionString function would perform some logic to manipulate the default connection string and return the correct value based on that id from the user token. This works fine and when run with the appropriate token, is able to switch connection strings ok.

The part I am unsure of is how to maintain each database individually - is there a good way to run migrations for each of the databases? I know that a connection string can be passed in to the do.net ef migrations... command, however if the amount of databases grows to a decent number this does not seem efficient.

Is the best bet to just bite the bullet and perform the migrations manually? Or would it be possible to somehow loop through a collection of keys which would return the connection string value and apply the migration to each?

I am relatively new to anything more than a simple dataset in EF so I am hoping I am not just missing something.

Thanks in advance

I have never done this, but You can try start migration for all dbs with one DbContext(said that the bases are the same), just try to change the connection string for each db. I don't have time to test it, but I hope it will work

foreach (var connection in ConnectionList)
{
    var optionBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
    optionBuilder.UseSqlServer(connection);

    using var dbContext = new ApplicationDbContext(optionBuilder.Options);
    var pendingMigrations = await dbContext.Database.GetPendingMigrationsAsync();

    if(pendingMigrations.Any())
    {
        await dbContext.Database.MigrateAsync();
    }

    await dbContext.DisposeAsync();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM