[英]LINQ dynamic query for entity framework
I have two Guid collections: 我有两个Guid集合:
List<Guid> statuses;
List<Guid> priorities;
How to make the following query: 如何进行以下查询:
var result = context.Activity.Where(a =>
(a.StatusID == statuses[0] || a.StatusID == statuses[1] || ... || a.StatusID == statuses[n]) &&
(a.PriorityID == priorities[0] || a.PriorityID == priorities[1] || ... || a.PriorityID == priorities[m]))
Collections could be empty and in this case we shouldn't add an appropriate 'AND' condition. 集合可能为空,在这种情况下,我们不应该添加适当的“ AND”条件。 How to do such dynamic query?
怎样做这样的动态查询?
UPDATE 更新
Hmm, imagine I need something like this: 嗯,想象一下我需要这样的东西:
List<Func<Activity, bool>> conds = new List<Func<Activity, bool>>();
var result = context.Activity.Where(conds[0] || (conds[1] && conds[2]))
How to do that? 怎么做?
First answer based on question 根据问题的第一个答案
Selects only those Activity
objects of which the StatusID
is in statusses
and the PriorityID
is in priorities
. 仅选择
StatusID
处于statusses
且PriorityID
处于priorities
PriorityID
那些Activity
对象。 Obviously if the collections are empty none of the Activity
objects will match the condition. 显然,如果集合为空,则所有
Activity
对象都不符合条件。
var result = context.Activity.Where(a =>
statuses.Contains(a.StatusID) && priorities.Contains(a.PriorityID));
Alternative answer based on @Don Tomato's comment 基于@Don Tomato的评论的替代答案
There must have been a misunderstanding based on the way you formulated the question. 根据您提出问题的方式一定存在误解。 However, I think what you want is to add conditions to an
IQueryable
as required. 但是,我认为您想要的是根据需要向
IQueryable
添加条件。
List<Func<Activity, bool>> conditions = new List<Func<Activity, bool>>();
// add conditions to the list
// for eaxmple:
// conditions.add(a => statuses.Contains(a.StatusID));
// or
// conditions.add(a => a.Name == "Don Tomato");
IQueryable query = context.Activity.AsQueryable();
foreach (Func<Activity, bool> condition in conditions)
query = query.Where(condition);
List<Activity> result = query.ToList();
You can chain where clauses together like this and the end result is that they will be anded together: 您可以像这样将where子句链接在一起,最终结果是将它们合并在一起:
var query = context.Activity.Where(o => <condition1>);
if (2ndconditionrequired)
{
query = query.where(o => <condition2>);
}
query.ToList();
You could also do it like this: 您也可以这样:
var result = context.Activity;
if (statuses != null && statuses.Count > 0)
{
result = results.Where(a =>
a.StatusID == statuses[0] || a.StatusID == statuses[1] || ... || a.StatusID == statuses[n];
}
if (priorities != null && priorities.Count > 0)
{
result = results.Where(a =>
a.PriorityID == priorities[0] || a.PriorityID == priorities[1] || ... || a.PriorityID == priorities[m]);
}
result.ToList(); // The query won't be executed until here.
But I guess what you really want to do is as @Bazzz answered. 但是我想您真正想要做的就是@Bazzz回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.