Demo Entities格式:其中OrgCode字段是Json类型
[{ "Id": "AAAA", "Name": "门店A会员卡", "OrgCode": [{ "OrgCodes": ["02873"], "BrandCode": "01747" }], "IsEnable": 1 }, { "Id": "BBBB", "Name": "门店B会员卡", "OrgCode": [{ "OrgCodes": ["00777", "02873"], "BrandCode": "01747" }], "IsEnable": 1 } ]
想要使用LINQ用OrgCode字段中的BrandCode值做筛选,有两种办法:
// PS:SQL语句写法
SELECT * FROM TableDemo WHERE JSON_CONTAINS(OrgCode, JSON_OBJECT('BrandCode','01747'))
→ 用法 JSON_CONTAINS([json字段名], JSON_OBJECT([json中的指定字段名],[判断参数值]))
(一)假如json是动态变化的,转化成JObject类型做筛选
// Json字符串 var Json = "上文DemoEntities"; var test = JsonConvert.DeserializeObject<JObject>(json); var code = test ["BrandCode"].Value<int>(); // LINQ从数据库查 var test = DBRep.Change<DemoTable>().DetachedEntities.Where(e => e.IsEnable)
.Select(e => JsonConvert.DeserializeObject<JObject>(e.OrgCode))
.Where(s => s["BrandCode"].Value<string>() == "01747")
.FirstOrDefault();
(二)假如是规范的,反序列化为C#对象再做筛选(此方法缺点是必须先定义反序列化对象格式)
// Json字符串 var json = "上文DemoEntities"; var test = JsonConvert.DeserializeObject<Content>(json); Value value = test.OrgCodeJson.FirstOrDefault(x => x.BrandCode.Equals("01747", StringComparison.InvariantCultureIgnoreCase)); public class Content { public string Id { get; set; } public List<Value> OrgCodeJson { get; set; } public Content() { OrgCodeJson = new List<Value>(); } } public class Value { public List<string> OrgCodes { get; set; } public string BrandCode { get; set; } }
// LINQ从数据库查
var test = DBRep.Change<DemoTable>().DetachedEntities.Where(e => e.IsEnable)
.Select(e => JsonConvert.DeserializeObject<Content>(e.OrgCode))
.Where(s => s.BrandCode == "01747")
.FirstOrDefault();
参考文档:C# linq 查询json