【问题标题】:List of predicates in Entity Framework Where clause [duplicate]实体框架 Where 子句中的谓词列表 [重复]
【发布时间】:2016-05-03 15:14:27
【问题描述】:
List<System.Linq.Expressions.Expression<Func<MyType, bool>>> lstPredicates = new List<System.Linq.Expressions.Expression<Func<MyType, bool>>>();

foreach (MyType myAccount in lstMyType)
{
    System.Linq.Expressions.Expression<Func<MyType, bool>> predicate = 
        t => t.Account == myAccount.Account && t.Branch == myAccount.Branch;
    lstPredicates.Add(predicate);
}

lstTransactions = Context.MyTrans
   .Where(lstPredicates)
   .ToList();

我试图在MyTrans 表中只运行一次查找,所以我正在建立一个谓词列表。我想在交易中存在任何帐户和分支组合的列表中检索交易。

即我正在尝试生成一个谓词,例如

predicate = t => 
    (t.Account == 123 && t.Branch == London) 
    || (t.Account == 433 && t.Branch == Manchester)
    ||...

【问题讨论】:

  • 我会考虑只使用一个表达式和 .Contains()。示例 Where(x => yourListOfIDs.Contains(x.Account)

标签: c# entity-framework linq linq-to-entities predicate


【解决方案1】:

您可以使用Linqkit 库。使用PredicateBuilder,您可以执行以下操作:

 var predicate = PredicateBuilder.False<MyType>();

 foreach (MyType myAccount in lstMyType)
 {
   predicate = predicate.Or (
        t => t.Account == myAccount.Account && t.Branch == myAccount.Branch);
 }

var query= Context.MyTrans.AsExpandable().Where(predicate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多