尝试根据存储在另一个表中的当前状态选择订单。继续获取所有订单而不是按当前状态筛选的订单。当状态不为空时,查询应根据订单的最新状态进行过滤,我认为该状态应按照记录日期的第一个状态的降序排列。
private IQueryable<order_tbl> CreateQuery(string status, int? orderId, DateTime? orderDate) {
var query = from o in context.order_tbl select o;
if (orderId.HasValue) query = query.Where(w => w.id.Equals(orderId.Value));
if (orderDate.HasValue) query = query.Where(w => w.OrderDate.Equals(orderDate.Value));
if (!string.IsNullOrEmpty(status)) {
query = (from q in query
from s in q.order_status
.OrderByDescending(o => o.DateStatusUpdated)
.Take(1)
.Where(w => w.Status.Equals(status))
select q);
}
return query;
}
表格中有更多字段,为简洁起见,我省略了这些字段。
order_tbl
id date customerId
1 2/1/2018 6
2 2/3/2018 5
3 2/6/2018 3
ORDER_STATUS
id orderId DateStatusUpdated status
1 1 2/1/2018 open
2 1 2/2/2018 filled
3 2 2/3/2018 open
4 2 2/4/2018 filled
5 3 2/6/2018 open
仅在&#39; open&#39;上搜索时,查询将返回订单1,2,3,而不仅仅是订单3.查询状态有什么问题?
答案 0 :(得分:0)
这个答案指出了我正确的方向,LINQ Query - Only get Order and MAX Date from Child Collection
将我的查询修改为以下内容。
if (!string.IsNullOrEmpty(status)) {
{
query = query
.SelectMany(s => s.order_status
.OrderByDescending(o => o.DateStatusUpdated)
.Take(1)
)
.Where(w => w.Status.Equals(status))
.Select(s => s.order_tbl);
}