EF Core 7添加迁移时遇‘Fragment’方法未实现异常求助
EF Core 7.0 RC1添加迁移时System.TypeLoadException的解决指引
错误详情
System.TypeLoadException: Method 'Fragment' in type 'Microsoft.EntityFrameworkCore.Design.Internal.CSharpHelper' from assembly 'Microsoft.EntityFrameworkCore.Design, Version=6.0.8.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation. at Microsoft.EntityFrameworkCore.Design.DesignTimeServiceCollectionExtensions.<>c__DisplayClass0_0.<AddEntityFrameworkDesignTimeServices>b__0(ServiceCollectionMap services) at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.TryAddProviderSpecificServices(Action`1 serviceMap) at Microsoft.EntityFrameworkCore.Design.DesignTimeServiceCollectionExtensions.AddEntityFrameworkDesignTimeServices(IServiceCollection services, IOperationReporter reporter, Func`1 applicationServiceProviderAccessor) at Microsoft.EntityFrameworkCore.Design.Internal.DesignTimeServicesBuilder.CreateServiceCollection(DbContext context) at Microsoft.EntityFrameworkCore.Design.Internal.DesignTimeServicesBuilder.Build(DbContext context) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) Method 'Fragment' in type 'Microsoft.EntityFrameworkCore.Design.Internal.CSharpHelper' from assembly 'Microsoft.EntityFrameworkCore.Design, Version=6.0.8.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation.
问题原因
核心是EF Core版本不兼容:项目引用的EF Core Runtime为7.0.0-rc.1.22426.7,但迁移工具加载了旧版本(6.0.8)的Microsoft.EntityFrameworkCore.Design程序集,新旧版本的CSharpHelper类型存在方法定义差异,导致类型加载失败。
解决步骤
- 清理项目残留文件:删除项目目录下的
bin和obj文件夹,彻底清除可能残留的旧版本程序集 - 统一NuGet包版本:检查项目所有EF Core相关包(包括
Microsoft.EntityFrameworkCore、Microsoft.EntityFrameworkCore.Design、Microsoft.EntityFrameworkCore.SqlServer等)的版本,确保全部设置为7.0.0-rc.1.22426.7,禁止混合不同版本 - 同步全局
dotnet-ef工具版本:- 查看当前全局工具版本:
dotnet tool list --global - 若版本不匹配,先卸载旧版本:
dotnet tool uninstall --global dotnet-ef - 安装对应RC版本:
dotnet tool install --global dotnet-ef --version 7.0.0-rc.1.22426.7
- 查看当前全局工具版本:
- 重新生成解决方案后执行迁移命令:
dotnet ef migrations add [你的迁移名称]
额外检查
如果是多项目结构,需确保所有关联项目的EF Core包版本也保持一致,避免跨项目引用带来的版本冲突。
内容的提问来源于stack exchange,提问作者Stijn VH
相关产品推荐
相关产品推荐

