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

EF Core 5 不实现IDesignTimeDbContextFactory如何将迁移拆分到类库?

问题根因

你代码里的MigrationsAssembly方法参数传错了,这是报错的直接原因。
MigrationsAssembly方法要求传入的是迁移所在类库的程序集名称,但你传了typeof(TMSDbContext).AssemblyQualifiedName,这个值是包含完整类型信息、版本号、公钥标记的类型限定名,EF Core无法通过这个值正确加载程序集,所以抛出了System.IO.FileLoadException异常。


修复方案

不需要额外实现IDesignTimeDbContextFactory<T>接口,只需要修改扩展方法里的配置代码,把MigrationsAssembly的参数改成迁移类库的程序集名称即可:

public static IServiceCollection AddTMS(this IServiceCollection services, IConfiguration configuration)
{
    var tmsConfiguration = configuration.GetSection("TMS");

    services.AddDbContext<TMSDbContext>(opt =>
        {
            opt.UseSqlServer(tmsConfiguration.GetSection("ConnectionString").Value, sqlOpt =>
            {
                sqlOpt.MigrationsHistoryTable("_TMSMigrationsHistory");
                // 仅修改这一行参数即可
                sqlOpt.MigrationsAssembly(typeof(TMSDbContext).Assembly.FullName);
                // 也可以直接写迁移类库的程序集名,例如 sqlOpt.MigrationsAssembly("TMS");
            });
        });

    return services;
}

验证步骤

修改代码重新编译后,再执行你原来的迁移命令即可正常生成迁移:

dotnet ef migrations add InitialMigration --project .\TMS.csproj --startup-project ..\API\API.csproj --output-dir ./Database/Migrations --context TMSDbContext

额外排查点

如果修改后仍有报错,可检查两项配置:

  • 确保API项目的配置文件中已经正确配置TMS:ConnectionString节点的有效数据库连接字符串
  • 确保两个项目引用的所有EF Core相关依赖包版本完全一致,避免版本兼容问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 19:42:03