我的Linq查询需要额外的where子句。例如,如果客户选择日期过滤器,所以我需要过滤到我的查询等...当我尝试myQuery.Where谓词时,只有group by的字段可见。
如何在查询中附加新的where条件。
//for example i need dynamically append o.OrderDate==Datetime.Now or another where clause
var myQuery =(from o in _db.Orders
join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals
l.OrderId
where o.OrderDate.Value.Year == year1
group o by new {o.OrderDate.Value.Month}
into g
select
new
{
Month = g.Key.Month,
Total = g.Select(t => t.OrderLines.Sum(s => s.OrderTotal)).FirstOrDefault()
});
答案 0 :(得分:2)
在查询结束时你为时已晚,无法添加新的Where
。您已经对数据进行了分组并对其进行了投影,几乎删除了所有字段。
尝试:
var baseQuery = from o in _db.Orders
join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals l.OrderId
where o.OrderDate.Value.Year == year1
select new { Order = o, OrderLine = l };
if (something)
{
baseQuery = baseQuery.Where(x => x.Order.Foo == "Bar");
}
var myQuery = (from o in baseQuery
group o by new { o.Order.OrderDate.Value.Month }
into g
select
new
{
Month = g.Key.Month,
Total = g.Sum(t => t.OrderLine.OrderTotal)
});
显然,您可以拥有多个if
。每个.Where()
都在&&
(AND
)与其他条件。
请注意join
的结果是如何在具有两个属性的匿名类中投影的:Order
和OrderLine