Microsoft.EntityFrameworkCore报错问题
Microsoft.EntityFrameworkCore报错Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.AdHocMapper'
System.TypeLoadException:“Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.AdHocMapper' from assembly 'Microsoft.EntityFrameworkCore, Version=9.0.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.”
这个错误通常与EF Core版本不匹配有关,我需要检查项目的依赖配置。
我发现了问题所在,这是由于项目中的Entity Framework Core包版本不匹配导致的:
- Microsoft.EntityFrameworkCore 和 Microsoft.EntityFrameworkCore.Proxies 使用的是9.0.5版本
- Microsoft.EntityFrameworkCore.Tools 使用的是6.0.0版本
- Pomelo.EntityFrameworkCore.MySql 使用的是8.0.3版本 这些版本的不一致会导致类型加载错误。由于这是一个.NET 8项目,我们应该使用与.NET 8兼容的EF Core 8.x版本。让我们修改项目文件:
主要更改:
将 Microsoft.EntityFrameworkCore 降级到 8.0.3
将 Microsoft.EntityFrameworkCore.Proxies 降级到 8.0.3
将 Microsoft.EntityFrameworkCore.Tools 升级到 8.0.3 这样所有EF Core相关的包版本就统一了,应该能解决类型加载错误的问题。修改后,请:
保存文件
运行 dotnet restore 重新还原包
重新编译并运行项目 这样应该就能解决启动时的类型加载错误了。
System.TypeLoadException:“Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.AdHocMapper' from assembly 'Microsoft.EntityFrameworkCore, Version=9.0.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.”
Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.AdHocMapper'
answer
Hi @Misha Kurytsia, not sure if you found the answer, I was getting the same error with 9.0.3. I followed article https://github.com/dotnet/efcore/issues/35179 and switched back to 8.0.11 for EF and MySQL.EF packages and got past the error.
迁移问题
检查Program.cs中的数据库初始化配置,看看是否正确启用了数据库迁移。
toolName: view_files
status: success
filePath: f:\Merchant\merchant202506\net8\Application\Application\Program.cs
我发现问题了。虽然代码中有 context.Database.Migrate(),但是看起来还没有创建迁移文件。在EF Core中,我们需要先创建迁移文件,然后才能执行迁移。
请按照以下步骤操作:
- 首先,确保已安装EF Core工具:
dotnet tool install --global dotnet-ef
- 在项目目录下创建初始迁移:
dotnet ef migrations add InitialCreate
- 然后手动应用迁移以创建数据库:
dotnet ef database update
如果执行过程中遇到错误,请确保:
- MySQL服务已经启动
- 连接字符串中的用户名和密码正确
- 数据库 'swdigit' 已经存在(如果不存在,需要先创建)
创建数据库的MySQL命令是:
CREATE DATABASE swdigit CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
完成这些步骤后,再重新运行应用程序,数据库表应该就能正确创建了。
使用c#语言,开发一款答题系统,需要包含用户注册(注册信息有用户名,登录密码,所在部门,电话号码等信息),
后台管理(用户权限管理,分为普通用户和管理员用户和题库管理用户,管理员用户可以更新题库和管理人员权限,重置密码等,题库管理用户可以开展每日答题活动或考试,并可以更新题库),
答题系统(有每日答题模块和考试两个模块,需要根据管理员设置自动生成答卷,可以限制答题时长,提交后系统能自动生成考分并显示做错题目及正确答案),
排行榜,
分为每日答题(可以设置每天从题库里随机摘取几道题,累计每日得分)和考试两个排行榜。题库管理(管理每日答题活动或考试,更新题库,题库分几类可自行添加,如网络安全、保密知识、安全生产等,可设有单选、多选、判断等题型。)。错题管理(自动记录错题形成错题集)