我的数据库中有这种关系:
Order => historyStatus => Status
Order
包含HistoryStatus
和HistoryStatus
的列表,其中包含一个Status
。
我的使用案例是:使用确定的Order
搜索所有Status
并获取最新的HistoryStatus
(基于日期)
我如何在linq中实体和IQueryable
?
以下是实体:
public class Order
{
public int ID { get; set; }
public virtual ICollection<HistoryStatusOrder> HistoriesStatusOrder { get; set; }
}
public class HistoryStatusOrder
{
public int ID { get; set; }
public DateTime Date { get; set; }
public string StatusOrderCode { get;
public int OrderId { get; set; }
public virtual StatusOrder StatusOrder { get; set; }
public virtual Order Order { get; set; }
}
public class StatusOrder : IEntityBase<string>
{
public string ID { get; set; }
public virtual ICollection<HistoryStatusOrder> HistoriesStatusOrder { get; set; }
}
这是我的Search
方法:
// do multiple searches
if (searchOrderVM.OrderNumber != null)
queryable = queryable.Where(x => x.OrderNumber.ToString().Contains(searchOrderVM.OrderNumber.ToString()));
// Next
if (searchOrderVM.SelectedOrdersStatus != null)
{
// Need to return queryable = ....
}
// Next search...
....
// Finally I do .ToList() to launch the query in database.
感谢您的帮助:)
答案 0 :(得分:2)
这会找到所有Orders
,其中HistoryStatusOrder
的最新Order
具有特定的StatusOrderCode
:
var results = orders.Where (o => o.HistoriesStatusOrder
.OrderByDescending (hso => hso.Date)
.First().StatusOrderCode == "foobar");
(假设每个Order
始终至少有一个HistoryStatusOrder
)
您可以使用其他方式编写此查询以保留IQueryable<Order>
:
var results = orders
.Select (o => new {
Order = o,
LatestHistoryStatusOrder = o.HistoriesStatusOrder
.OrderByDescending (hso => hso.Date)
.First()
})
.Where (x => x.LatestHistoryStatusOrder.StatusOrderCode == "foobar")
.Select (x => x.Order);
foreach(var order in results)
{
// Here you can access:
// order.ID
}
如果您想继续访问LatestHistoryStatusOrder
,可以跳过上一个.Select(x => x.Order)
声明:
var results = orders
.Select (o => new {
Order = o,
LatestHistoryStatusOrder = o.HistoriesStatusOrder
.OrderByDescending (hso => hso.Date)
.First()
})
.Where (x => x.LatestHistoryStatusOrder.StatusOrderCode == "foobar");
foreach(var item in results)
{
// Here you can access:
// item.Order.ID
// item.LatestHistoryStatusOrder
}