[英]EF Core 2, .NET CORE 2 :How do I query the same column for multiple conditions using IQueryable<T>?
我有一个类似于下图中的数据库表
我将传递 UserId 和 2 个字符串。 例如: userId: 1 , key1: h1 , key2: h2到具有类似签名的 APi。
Public List<T> CheckValuesForUser(string userId, string key1, string key2)
我需要检查特定的 userId 1 是否同时具有 h1 和 h2 值。 如果用户没有两个密钥,则查询应返回 null。
我尝试了以下查询,
context.tableName.where(i=> i.value.Equals("h1") && i.value.Equals("h2"))
- 这不返回任何内容。 我假设这个谓词是为每一行执行的。Context.tableName.Where(i=> new string[]{ Key1,Key2 }.Contains(i.Value))
-- 即使用户没有 Key2 的值,它也会返回一个值。 如果用户没有两个键,我需要得到 NULL 结果。var list1= Context.tableName.Where(i=> i.Value.Equals(key1)).toList(); var list2= Context.tableName.Where(i=> i.Value.Equals(Key2)).toList(); if(list1.Count > 0 && list2.Count > 0) list1.AddRange(list2);
有人可以帮我找到更好的解决方案吗? 我正在使用Asp.Net Core 2.2
因为 h1 和 h2 条目是单独的记录,所以您需要分别检查这两个值。
// Group the records by the expected UserId
var groupedRecords = context
.TableName
.Where(t => t.UserId == userId)
.GroupBy(t => t.UserId);
// Ensure both the required records exist within the grouping
var hasRequiredRecords = groupedRecords.Any(i => i.Value.Equals("h1"))
&& Any(i => i.Value.Equals("h2"))
// Now that you know you have the required values, return them
return groupedRecords.Where(i => i.Value.Equals("h1") && i.Value.Equals("h2");
最后一行将只返回作为单个List<T>
提供的userId
的值h1
和h2
的两条记录
你可以试试这个代码来得到你想要的:
string[] keys = new string[] { key1, key2 };
var result = (from m in context.UserInfo
where m.UserId == userId && keys.Any(name => name.Equals(m.Value)) select m).ToList().Count < keys.Count() ? null :
(from m in context.UserInfo where m.UserId == userId && keys.Any(name => name.Equals(m.Value)) select m).ToList();
不满足条件时,接收结果为null,如果满足,则返回对应的数据集给结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.