【问题标题】:Adding optional where parameter to query based linq query向基于查询的 linq 查询添加可选的 where 参数
【发布时间】:2018-04-03 05:44:45
【问题描述】:

我正在尝试使用来自LINQ to SQL Where Clause Optional Criteria的答案

我喜欢我的 linq 使用基于查询的语法。不知道如何使用 whereif。

我的查询看起来像这样

var result = (from tran in _ctx.Transactions where tran.Id == transactionId select tran);

有时会投射出来

var result = (from tran in _ctx.Transactions where tran.Id == transactionId
     select new Abstract
           {
               tran.Date,
               tran.Key
           });

我可以使用方法语法做一个可选的过滤器

var result = _ctx.Transactions
             .where(t=>t.Id == transactionId)
             .whereIf(tran.Dept!= "AllDept", x => x.Dept== deptName);

不确定如何在基于查询的 linq 查询中使用 WhereIf。

【问题讨论】:

  • 参见stackoverflow.com/questions/279701/… 讨论哪种语法更好,特别是在您扩展它时。
  • 那个语法很残缺,所以你能做的最好的就是:from tran in _ctx.Transactions.WhereIf(..., tran => tran.Id == transactionId) select tran(所以是两种语法的混合)。

标签: c# linq


【解决方案1】:

阅读:Dynamic query with Linq

我建议使用 PredicateBulder 并为您的查询添加谓词,如下所示,这将使用可变谓词动态构建查询

var predicate = PredicateBuilder.True<Transaction>();  
predicate = predicate.And(t=>t.Id == transactionId);  
if (!string.IsNullOrEmpty(department))  
{  
    predicate = predicate.And(tran => tran.Dept!= "AllDept");  
}
var result = _ctx.Transactions.where(predicate);

Dynamically Composing Expression Predicates

【讨论】:

  • 出现投影怎么办?假设我在查询中使用连接,例如 var tran = (from t in _ctx.transactions join type in _ctx.TranType on t.key equals type.key select new Abstract {t.date, type.name}); 现在我想根据 tranType 上的可选过滤器进行过滤。?
  • @Navyseal - 如果在给定的查询中您想添加基于 tranType 的过滤器,那么 trantype 是否来自查询??
  • tranType 是另一个我希望加入事务的表。实际上我有多个连接。但为简洁起见,假设我有两个表 transaction 和 transactionType,我的过滤器基于 Transaction 中的 Id,我想在 TransactionType.Name 上添加一个可选过滤器,前提是函数参数没有说“AllTypes”和如果参数说“AllTypes”,我会省略过滤器。所有这些都需要投影到另一个“AbstractTransaction”类中。我如何使用谓词构建器来做到这一点?
  • @Navyseal - 没有获得代码的实际视图,但需要这样做if (transtype == "AllTypes") { predicate = predicate.And(tran =&gt; condition you want); }
猜你喜欢
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 2020-01-08
相关资源
最近更新 更多