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

EF Core测试场景切换Schema后迁移未执行问题排查

问题排查与解决方案

1. 首要原因:未指定迁移程序集

EF Core 默认会从当前 DbContext 所在的测试程序集查找迁移文件,而你的迁移文件通常存放在业务项目中,导致调用Migrate()时找不到任何待执行的迁移,自然无操作也无报错。
修改BuildOptions方法,在UseSqlServer配置中指定迁移所在的程序集即可:

private DbContextOptions BuildOptions(string schema)
{
    return new DbContextOptionsBuilder<TestMyDbContext>()
        .UseSqlServer(SqlDatabaseHandler.BuildSchemaConnectionStringForDatabase(testsBase.DatabaseName, schema),
            builder => 
            {
                builder.MigrationsHistoryTable("__EFMigrationsHistory", schema);
                // 替换为你实际存放Migration文件夹的业务项目程序集名称
                builder.MigrationsAssembly("你的业务项目程序集名称");
                // 如果迁移对应的是业务项目的原生DbContext而非TestMyDbContext,补充这行
                builder.MigrationsAssembly(typeof(你的业务原生DbContext).Assembly.FullName);
            })
        .ConfigureWarnings(x => x.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning))
        .Options;
}

2. 连接字符串配置校验

你创建登录时指定了DEFAULT_DATABASE=[master],需要确认BuildSchemaConnectionStringForDatabase方法返回的连接字符串明确指定了Database=你的业务库名,否则迁移会默认执行到master库,导致业务库无表生成。

3. 清理迁移文件硬编码Schema

检查业务项目Migrations文件夹下的迁移文件,确认所有CreateTable、AlterTable等操作没有硬编码schema: "dbo"参数,如果存在则删除该参数,让迁移使用DbContext中动态指定的默认Schema。

4. 日志定位可选方案

临时把NullLoggerFactory换成控制台日志输出,可直接查看迁移执行的全流程日志,快速定位异常环节:

// 替换原有loggerFactory定义
private static ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());

其他代码bug修正

你当前代码存在大小写赋值错误,会导致DatabaseName取值异常:

// 原错误代码
private readonly TestsBase testsBase;
public TestsTearDown(TestsBase testsBase)
{
    this.TestsBase = testsBase; // 赋值给了不存在的大写属性
}
// 修正为
public TestsTearDown(TestsBase testsBase)
{
    this.testsBase = testsBase;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:54:01