You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ABP.io多租户应用中仓储未使用租户数据库问题排查

多租户数据种子写入默认数据库问题

使用ABP.io(非商业版)构建多租户应用,已实现迁移服务为每个租户创建独立数据库,自定义InjectableCloudDbContextFactory从租户仓储获取连接字符串。迁移器可成功为每个租户生成带表的数据库,但数据种子器通过Jobs Repository添加数据时,无论当前租户(已确认已设置)如何,所有数据都会写入初始的默认数据库。原本以为仓储会自动获取正确的DbContext,也尝试过在DbContext中配置OnConfiguring,以及直接通过服务提供者获取DbContext执行迁移,但问题仍未解决。

相关代码

InjectableCloudDbContextFactory

public class InjectableCloudDbContextFactory : IDbContextFactory<CloudDbContext>, ITransientDependency
{
    private readonly ICurrentTenant _tenant;
    private readonly ITenantStore _tenantStore;
    private readonly IConfiguration _configuration;

    public InjectableCloudDbContextFactory(ICurrentTenant tenant, ITenantStore tenantStore,
        IConfiguration configuration)
    {
        _tenant = tenant;
        _tenantStore = tenantStore;
        _configuration = configuration;
    }

    //This one is used by our migration service
    public CloudDbContext CreateDbContext()
    {
        var connectionString = _configuration.GetConnectionString("Default");
        var tenantId = _tenant.Id;
        if (tenantId.HasValue)
        {
            var tenant = _tenantStore.Find(tenantId.Value);

            var tenantConnectionStrings = tenant.ConnectionStrings
                .Select(x => x.Value)
                .ToList();
            if (tenantConnectionStrings.Count >= 1)
            {
                connectionString = tenantConnectionStrings.First();
            }
        }


        var builder = new DbContextOptionsBuilder<CloudDbContext>()
            //this needs to get connection string for each tenant - this might work!?
            .UseSqlServer(connectionString);

        return new CloudDbContext(builder.Options);
    }
}

EntityFrameworkCoreV2DbSchemaMigrator

public class EntityFrameworkCoreV2DbSchemaMigrator
    : IV2DbSchemaMigrator, ITransientDependency
{
    private readonly IServiceProvider _serviceProvider;
    private readonly InjectableCloudDbContextFactory _contextFactory;

    public EntityFrameworkCoreV2DbSchemaMigrator(
        IServiceProvider serviceProvider, InjectableCloudDbContextFactory contextFactory)
    {
        _serviceProvider = serviceProvider;
        _contextFactory = contextFactory;
    }

    public async Task MigrateAsync()
    {
        await _contextFactory.CreateDbContext().Database.MigrateAsync();
    }
}

尝试过的替代代码

await _serviceProvider
            .GetRequiredService<ClikHostDbContext>()
            .Database
            .MigrateAsync();

内容的提问来源于stack exchange,提问作者gregWart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:52:47