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

EF Core脚手架时出现‘Cannot Load Assembly’错误求助

问题:Code First正常运行但Scaffold-DbContext时出现程序集加载错误

采用Code First方式可正常添加迁移并更新数据库,但尝试通过脚手架生成新数据库时,出现程序集加载失败的错误。


相关配置代码

Lairage.Blazor项目Startup.cs

// Add the Innova Connection
services.AddContext<InnovaContext>(Configuration.GetConnectionString("InnovaConnection"));

Lairage.Context.Sql项目ServiceCollectionExtentions.cs

public static class ServiceCollectionExtentions
{
        
        public static IServiceCollection AddContext<TContext>(this IServiceCollection services, string connectionstring, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped) where TContext : DbContext => services
            .AddDbContext<TContext>(options => options.UseSqlServer(
                    connectionstring,
                    actions => actions.MigrationsAssembly("Lairage.Context.Sql")
                                      .EnableRetryOnFailure()
                ), serviceLifetime);

}

错误提示

Could not load assembly 'Lairage.Context.Sql'. Ensure it is referenced by the startup project 'Lairage.Blazor'.


执行环境与命令

  • 包管理器默认项目已设置为Lairage.Context.Sql
  • 执行的脚手架命令:
Scaffold-DbContext "Server=<***>;Initial Catalog=<***>;MultipleActiveResultSets=true;Integrated Security=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Innova

排查与解决方案

1. 确保启动项目引用目标程序集

Scaffold命令会以启动项目(此处为Lairage.Blazor)为入口加载依赖,即使包管理器默认项目设为Lairage.Context.Sql也不例外:

  • 右键Lairage.Blazor项目 → 「添加」→「项目引用」
  • 在弹出窗口中勾选Lairage.Context.Sql,保存后重新执行命令。

2. 显式指定迁移程序集参数

若已添加引用仍报错,可在Scaffold命令中显式指定迁移程序集,避免EF Core自动解析异常:

Scaffold-DbContext "Server=<***>;Initial Catalog=<***>;MultipleActiveResultSets=true;Integrated Security=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Innova -MigrationsAssembly Lairage.Context.Sql

3. 清理重建解决方案

项目依赖缓存可能导致程序集加载异常:

  • 右键解决方案 → 「清理解决方案」
  • 再右键解决方案 → 「生成解决方案」
  • 之后重新执行Scaffold命令。

4. 核对程序集名称一致性

确认Lairage.Context.Sql项目的程序集名称与代码中MigrationsAssembly("Lairage.Context.Sql")完全匹配:

  • 右键Lairage.Context.Sql项目 → 「属性」
  • 在「应用程序」标签页查看「程序集名称」,排查拼写错误或额外后缀。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:27:12