我正在使用LinqPad和Entity Framework 4模型以及MS SQL 2008数据库。
假设我们有一个Customer实体,它与Purchase的关联与Customer.CustomerID的外键。
以下linq生成ObjectQuery<Customer>
Purchases
与EntityCollection<Purchase>
的关联。
from c in Customers.Include("Purchases")
select c
现在我希望只使用最近购买的所有客户。如果没有购买,那么我希望Purchases
集合为空。
我需要类似下面的东西,但是它维护着实体和关联。我希望所有客户的收集限制为0或1次购买。
from c in Customers
from p in c.Purchases.Where(p => p.PurchaseDate == c.Purchases.Max(m => m.PurchaseDate).DefaultIfEmpty()
select new { CustomerID = c.CustomerID, PurchaseID = (int?)p.PurchaseID }
在我的服务中,我返回List<Customer>
,因此我认为我需要在linq查询的返回中维护Customer
实体和Purchases
关联。
用例:
var customers = CustomerService.GetCustomersAndMostRecentOrder();
foreach (Customer c in customers) {
Console.WriteLine(c.Lastname + ":" +
c.Purchases.Count() == 0 ? "None" : c.Purchases[0].PurchaseOrder);
}
感谢您的见解。
答案 0 :(得分:0)
您需要使用linq-to-entities执行部分查询,而使用linq-to-objects执行其余操作,如下所示:
var query = (from c in Customers
select new
{
Customer = c,
Purchase = c.Purchases.OrderByDescending(p => p.PurchaseDate).FirstOrDefault()
})
.AsEnumerable()
.Select(c => new Customer()
{
CustomerID = c.CustomerID,
CustomerProperty2 = c.CustomerProperty2,
CustomerProperty3 = c.CustomerProperty3,
...,
Purchases = new Purchase[] { c.Purchase }
}
);