[英]linq - get most recent associated record
假設我有Customer
和Order
對象,其中一個Customer
可以有許多Orders
(因此Order
類具有CustomerId
屬性),並且我想返回所有CustomerAndMostRecentOrder
對象的集合,這些對象的定義如下:
public class CustomerAndMostRecentOrder
{
public Customer Customer { get; set; }
public Order MostRecentOrder { get; set; }
}
我將如何編寫一個執行此操作的Linq查詢(我正在使用Linq to SQL)?
您可以使用以下查詢:
from c in customers
select new CustomerAndMostRecentOrder
{
Customer = c,
MostRecentOrder = c.Orders.OrderByDescending(o => o.PurchaseDate).FirstOrDefault()
};
這將使用從客戶到訂單的導航屬性。 通過在某些DateTime屬性上對Orders排序,然后加載第一個,來獲取MostRecentOrder。
您需要在Order
表中有一個CreatedDate
日期才能獲取最新的訂單。 然后,要獲取CustomerAndMostRecentOrder
對象,請執行以下查詢:
from c in customers
join o in orders on c.ID equals o.CustomerID into co
select new CustomerAndMostRecentOrder
{
Customer = c,
MostRecentOrder = co.OrderByDescending(o => o.CreatedDate).FirstOrDefault()
}
public class CustomerAndMostRecentOrder
{
public CustomerAndMostRecentOrder(Customer customer, Order mostRecentOrder)
{
Customer = customer;
MostRecentOrder = mostRecentOrder;
}
public Customer Customer { get; set; }
public Order MostRecentOrder { get; set; }
}
public class Order
{
}
public class Customer
{
public IEnumerable<Order> GetOrders()
{
}
}
public static class UsageClass
{
public static void Sample(IEnumerable<Customer> allCustomers)
{
IEnumerable<CustomerAndMostRecentOrder> customerAndMostRecentOrders =
allCustomers.Select(customer => new CustomerAndMostRecentOrder(customer, customer.GetOrders().Last()));
}
}
作為另一種選擇,您可能需要看一下http://msdn.microsoft.com/zh-cn/library/system.data.linq.dataloadoptions.associatewith.aspx上討論的DataLoadOptions.AssociateWith。 只需在上下文中設置您的需求,就不必擔心在查詢級別過濾子級。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.