Reputation: 2020
I currently have a .net core web api that has a SQL Server database per client. An api key is required to be passed in for every call and then is looked up in a master tenant database to get the correct connection string. The api will then set the connection string in the startup file and run the call.
Within the api, I have an endpoint that allows me to update all tenants to the latest migration and I also have a console app that will do the same. Something like this:
public async Task UpdateAllDatabases()
{
var qry = await GetAll(null, true);
foreach (var i in qry)
{
var optionsBuilder = new DbContextOptionsBuilder<MigrationContext>()
.UseSqlServer(i.DatabaseConnectionString);
using (var tenantContext = new MigrationContext(optionsBuilder.Options, _appSettings))
{
tenantContext.Database.Migrate();
}
}
}
The issue I am having is when I need to remove-migration
. How can I remove a migration from all tenant databases?
Upvotes: 0
Views: 553
Reputation: 1
i'm resloved
EFCoreMigrateMultiDatabase
this is my demo,need replace service IMigrationsScaffolder
and IMigrationsAssembly
support different database with single dbcontext to migration
Upvotes: 0
Reputation: 109
You can use the same Migrate method but with the parameter ‘targetMigration’.
This will upgrade or rollback all databases to the specified target migration.
public void Migrate (string targetMigration = null);
Update: added example
MigrationContext.cs
public class MigrationContext : DbContext
{
}
Execute migrations
using (var tenantContext = new MigrationContext())
{
tenantContext.Database.GetService<IMigrator>().Migrate("targetMigration");
}
.csproj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.4" />
</ItemGroup>
</Project>
Upvotes: 1