[英]Entity Framework with dynamic value set in where clause not working
我的数据库和相应的 class 结构如下
Class Helper:
List<Util> UtilityInfo,
Class Util :
int Id
我有以下值的过滤器数组
int[] idArray = { 1, 2, 3};
预期的查询格式:
_dbContent.Helper.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id = 1 || ut => ut.Util.id == 2 || ut => ut.Util.id == 3));
我想通过在 id 的数组上循环来实现相同的目的。
当我执行上面的查询时,它工作正常,但想使用循环动态构造相同的。
我尝试使用以下模式,但它在[ut.Util.id == item]
添加了一些 class 级别的表达式,在 Visual Studio 中观察到相同的调试表达式内容。
最后因为在检索数据时出现错误。
var helperInfo = new List<Helper>()
foreach(var item in idArray)
{
helperInfo = helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id == item));
}
注意:我已经成功完成了下面的模式,但希望通过循环实现相同的目标
helper= helper.Where
(
hp => idArray.Any
(
uId => hp.utilityInfo!= null &&
v.utilityInfo.Any
(
ut => ut.User != null &&
ut.Id == uId
)
)).ToList();
}
更新 2
您可以在下面的 prev 更新中通过相同的概念迭代IQueryable
或使用表达式
var helperInfo = _dbContent.Helper;
var filteredHelperInfo = new List<Helper>();
foreach(var item in idArray)
{
filteredHelperInfo.AddRange(helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id == item)).ToList());
}
如果我现在很好理解,如果您需要使用循环查询帮助列表,您需要创建新列表并在每次迭代中添加过滤项目,如下所示
注意:在您的第一次迭代中的代码中,您的列表将在第二次使用第一个 id 进行过滤时,您不会在第二个 id 的列表中找到任何项目,因此您的列表将为空
var helperInfo = new List<Helper>();
var filteredHelperInfo = new List<Helper>();
foreach(var item in idArray)
{
filteredHelperInfo.AddRange(helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id == item)));
}
更新
如果我现在很好理解,如果您需要使用循环查询帮助列表,您需要创建新列表并在每次迭代中添加过滤项目,如下所示
注意:在您的第一次迭代中的代码中,您的列表将在第二次使用第一个 id 进行过滤时,您不会在第二个 id 的列表中找到任何项目,因此您的列表将为空
var helperInfo = new List<Helper>();
var filteredHelperInfo = new List<Helper>();
foreach(var item in idArray)
{
filteredHelperInfo.AddRange(helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && ut.Util.id == item)));
}
最少代码的旧答案
您可以使用 contains 而不是像下面那样循环,这将获得您提到的数组中具有相同 id 的所有项目
helperInfo = helperInfo.Where(hp => hp.utilityInfo.Any(ut => ut != null && idArray.Contains( ut.Util.id)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.