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

EF Core更新数据库时出现KeyNotFoundException错误求助

解决思路

核心问题定位

这个错误是版本不兼容+MySQL驱动字符集bug导致的:

  • 项目目标框架是net6.0,但EF Core相关包用的是3.1.10,跨大版本的兼容性问题严重
  • 你使用的MySql.Data.EntityFrameworkCore 8.0.22(Oracle官方驱动)在.NET6环境下存在字符集编码字典的bug,17736是某个字符集的索引,驱动无法在字典中找到对应项
  • 同时引用了Microsoft.EntityFrameworkCore.SqlServer和MySQL的EF包,造成依赖冲突

具体解决步骤

  1. 清理并升级依赖包
    编辑你的.csproj文件,做以下修改:

    • 移除Microsoft.EntityFrameworkCore.SqlServer(你用的是MySQL,不需要SQL Server的EF驱动)
    • 将所有EF Core相关包升级到与net6.0匹配的6.0.x版本
    • 替换Oracle的MySQL驱动为更适配的Pomelo.EntityFrameworkCore.MySql(修复了大量字符集相关bug,对新版本.NET支持更完善)

    修改后的.csproj依赖示例:

    <Project Sdk="Microsoft.NET.Sdk.Web">
      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <Nullable>disable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <GenerateRuntimeConfigurationFiles>True</GenerateRuntimeConfigurationFiles>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.25" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.25">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.3" />
      </ItemGroup>
    </Project>
    

    注意:Pomelo的版本要和EF Core版本匹配,6.0.x系列对应.NET6

  2. 清理项目残留

    • 删除项目根目录下的bin和obj文件夹
    • 执行dotnet restore重新恢复依赖
  3. 重新执行迁移

    • 确保目标MySQL数据库已删除(或备份后清空)
    • 依次执行命令:
      dotnet ef migrations add addItemTable
      dotnet ef database update
      
  4. 额外优化(可选)
    在数据库连接字符串中添加CharSet=utf8mb4,避免字符集兼容性问题,示例:

    Server=your-server;Database=your-db;Uid=user;Pwd=password;CharSet=utf8mb4;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:35:18