EF Core 7 JSON列查询操作异常问题求助
EF Core 7 JSON列查询异常解决方案
问题原因
你在查询时先将UserIds和AuthorityCodes投影到匿名类型,再对匿名类型的UserIds调用Any方法,EF Core无法将这种操作翻译为针对JSON列的SQL查询。JSON列的LINQ查询需要直接作用于实体的原始导航属性,而非投影后的属性,否则EF无法识别对应的JSON列并生成正确的数据库JSON函数调用。
修复方案
调整查询逻辑,先过滤实体再执行投影,让EF Core能够正确解析JSON列的查询条件:
var result = _context.IdentitySchema // 先在实体层级过滤JSON数组 .Where(identity => identity.UserIds.Any(user => user.UserId == "1")) // 再投影需要的属性 .Select(identity => new { identity.UserIds, identity.AuthorityCodes }) .ToList();
额外检查点
- 确认
IdentitySchema类中UserIds的定义正确,应为List<UserAg>类型:
public class IdentitySchema { // 主键等其他必要属性 public int Id { get; set; } public List<UserAg> UserIds { get; set; } public List<AuthorityCode> AuthorityCodes { get; set; } // 对应你的AuthorityCodes类型 }
- 确保数据库提供程序支持JSON列查询(如SQL Server 2016+、PostgreSQL 10+等),EF Core 7对不同数据库的JSON函数翻译已做适配,但需保证数据库版本符合要求。
内容的提问来源于stack exchange,提问作者Zafer Kırık
相关产品推荐
相关产品推荐

