EF Core 7/8 JSON列使用Dictionary<string,string>绑定失败求助
问题:EF Core 7/8 JSON列绑定Dictionary<string,string>时异常
在使用EF Core 7/8的JSON列绑定功能时,仅实体类Entry中的PrimaryKey属性(类型为Dictionary<string,string>)出现异常,移除该属性后所有功能正常。已尝试相关方案但未解决,希望借助EF新特性完成绑定以支持后续对PrimaryKey字段的数据库查询,疑问:Dictionary类型是否不被支持?
相关JSON示例
{ "EntityFrameworkEvent": { "Entries":[ { "Name": "abc", "PrimaryKey": { "Name": "Jim"}, "Action": "Insert" }, { "Name": "jim", "PrimaryKey": { "Color": "Brown", "Hair":"Black"}, "Action": "Insert" } ] }, "Duration": 177 }
实体类及Fluent API配置代码(原代码)
public class Log { public long Id {get; set;} public Data {get; set;} // 缺少属性名 } public class Data { public EntityFrameworkEvent EntityFrameworkEvent {get; set;} public int Duration {get; set;} } public class EntityFrameworkEvent { public List<Entry> Entries {get; set;} } public class Entry { public string? Name {get; set;} public string? Action {get; set;} public Dictionary<string, string> PrimaryKey {get; set;} } modelBuilder.Enity<Log>(b => // 拼写错误:Entity { b.OwnsOne(x => x.Data, cb=> { cb.ToJson() // 缺少分号 cb.OwnsOne(x => x.EntityFrameworkEvent, ef => { ef.ToJson(); // 冗余的ToJson()配置 ef.OwnsMany(x => x.Entries); // 缺少分号 }) // 缺少分号 }) // 缺少分号 })
解决方案
EF Core 7/8完全支持在JSON列中使用Dictionary<string, string>类型,异常是由代码语法错误和配置冗余导致的,修正如下:
1. 修复实体类语法错误
- 为
Log类的Data属性补充属性名 - 初始化集合和Dictionary属性,避免空引用异常
- 补全所有缺少的分号
修正后的实体类:
public class Log { public long Id { get; set; } public Data Data { get; set; } // 补充属性名 } public class Data { public EntityFrameworkEvent EntityFrameworkEvent { get; set; } public int Duration { get; set; } } public class EntityFrameworkEvent { public List<Entry> Entries { get; set; } = new List<Entry>(); // 初始化集合 } public class Entry { public string? Name { get; set; } public string? Action { get; set; } public Dictionary<string, string> PrimaryKey { get; set; } = new Dictionary<string, string>(); // 初始化Dictionary }
2. 修正Fluent API配置
移除冗余的ToJson()调用——父级Data已配置为JSON列,其下的嵌套对象会自动包含在同一JSON结构中,重复配置会导致序列化逻辑冲突:
modelBuilder.Entity<Log>(b => { b.OwnsOne(x => x.Data, cb => { cb.ToJson(); cb.OwnsOne(x => x.EntityFrameworkEvent, ef => { ef.OwnsMany(x => x.Entries); }); }); });
3. 支持PrimaryKey字段查询
完成上述修正后,即可使用EF Core的JSON查询功能对PrimaryKey进行查询,例如:
var logs = await context.Logs .Where(l => EF.Functions.JsonContains(l.Data.EntityFrameworkEvent.Entries[0].PrimaryKey, "{\"Name\": \"Jim\"}")) .ToListAsync();
内容的提问来源于stack exchange,提问作者chobo2
相关产品推荐
相关产品推荐

