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

Entity Framework Core + Pomelo MySQL JSON列配置报错求助

解决Entity Framework Core + Pomelo MySQL JSON列配置冲突问题

问题原因

你同时使用了两种重复的配置逻辑:

  • Property(p => p.PicturesJson).HasColumnType("json") 手动声明属性为JSON列
  • OwnsOne(x => x.PicturesJson, builder => builder.ToJson()) 通过拥有者关系映射JSON列

Pomelo的ToJson()方法已经会自动将导航属性映射为MySQL的JSON列,手动添加Property()配置会导致EF Core尝试向Property实体添加重复的属性/导航项,从而抛出错误。

正确配置

移除手动指定列类型的代码,只保留OwnsOne的JSON映射配置即可:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Property>().OwnsOne(x => x.PicturesJson, builder => builder.ToJson());
}

额外说明

  1. 版本兼容性:EF Core 8建议搭配Pomelo.EntityFramework.MySql 8.x版本(正式版或预览版),你使用的7.0.0版本和EF Core 8存在跨大版本兼容风险,建议升级到Pomelo 8.x正式版(若已发布)或最新预览版。
  2. SQL Server与MySQL的差异:SQL Server的EF Core提供程序对重复配置的容忍度更高,内部处理逻辑不同所以未触发错误,但这并非标准配置方式。
  3. 可选优化:如果没有启用延迟加载,PicturesJson属性的virtual修饰可以移除,避免生成不必要的代理类。

内容的提问来源于stack exchange,提问作者pieter de villiers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:33:17