【问题标题】:EF-Core Single Deployment; Multiple Databases; MigrationsEF-Core 单一部署;多个数据库;迁移
【发布时间】:2019-06-03 20:15:46
【问题描述】:

我目前有一个 .net core web api,每个客户端都有一个 SQL Server 数据库。每次调用都需要传入一个 api 密钥,然后在主租户数据库中查找以获取正确的连接字符串。然后api将在启动文件中设置连接字符串并运行调用。

在 api 中,我有一个端点,允许我将所有租户更新到最新的迁移,我还有一个控制台应用程序可以执行相同的操作。像这样的:

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();
            }
        }
    }

我遇到的问题是何时需要remove-migration。如何从所有租户数据库中删除迁移?

【问题讨论】:

    标签: c# sql-server entity-framework-core


    【解决方案1】:

    您可以使用相同的 Migrate 方法,但使用参数“targetMigration”。

    这会将所有数据库升级或回滚到指定的目标迁移。

    public void Migrate (string targetMigration = null);
    

    (https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.migrations.imigrator.migrate)

    更新:添加示例

    MigrationContext.cs

    public class MigrationContext : DbContext
    {
    }
    

    执行迁移

    using (var tenantContext = new MigrationContext())
    {
        tenantContext.Database.GetService<IMigrator>().Migrate("targetMigration");
    }
    

    .csproj 文件

    <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>
    

    【讨论】:

    • 你能举个例子吗,因为我的tenantContext.Database.Migrate(); 没有字符串重载。
    • 您使用的是哪个版本的 .net core?以及哪个版本的实体框架核心?
    • Core 2.2 和 EF Core 2.2.4 - 您的解决方案正在运行。谢谢!
    猜你喜欢
    • 2019-08-03
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 2014-10-08
    • 2020-01-25
    • 2021-10-17
    相关资源
    最近更新 更多