LINQ动态查询实体框架

时间:2012-11-29 15:10:18

标签: linq entity-framework

我有两个Guid系列:

List<Guid> statuses;
List<Guid> priorities;

如何进行以下查询:

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]))

收藏可能是空的,在这种情况下,我们不应该添加适当的&#39; AND&#39;条件。怎么做这样的动态查询?

更新

嗯,想象一下我需要这样的东西:

List<Func<Activity, bool>> conds = new List<Func<Activity, bool>>();

var result = context.Activity.Where(conds[0] || (conds[1] && conds[2]))

怎么做?

3 个答案:

答案 0 :(得分:5)

基于问题的第一个答案
仅选择Activity StatusID位于statussesPriorityID位于priorities的{​​{1}}个对象。显然,如果集合是空的,Activity个对象都不会匹配条件。

var result = context.Activity.Where(a => 
    statuses.Contains(a.StatusID) && priorities.Contains(a.PriorityID));

基于@Don Tomato的评论的替代答案
根据你提出问题的方式,一定存在误解。但是,我认为您想要的是根据需要为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();

答案 1 :(得分:0)

您可以将where子句链接在一起,最终结果是它们将被合并在一起:

var query = context.Activity.Where(o => <condition1>);

if (2ndconditionrequired)
{
    query = query.where(o => <condition2>);
}

query.ToList();

答案 2 :(得分:0)

你也可以这样做:

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.

但我猜你真正想做的是@Bazzz回答。