开发者

Linq to Entities returning all outer entities and one or none associated entities

I'm using LinqPad with and Entity Framework 4 model and MS SQL 2008 database.

Suppose we have a Customer entity that has an association to Purchase with a foreign key to Customer.CustomerID.

The following linq produces an ObjectQuery<Customer> with Purchases association of EntityCollection<Purchase>.

from c in Customers.Include("Purchases")
select c

Now I want to get all customers with only the most recent purchase. If there is no purchase then I want the Purchases collection to be empty.

I need something like the following, but that maintains the entity and association. I want to get all the customers with a collection limited to 0 or 1 purchases.

from c in Customers
from p in c.Purchases.Where(p => p.PurchaseDate == c.Purchases.Max(m => m.PurchaseDate).DefaultIfEm开发者_运维技巧pty()
select new { CustomerID = c.CustomerID, PurchaseID = (int?)p.PurchaseID }

In my service I return a List<Customer>, so I think I need to maintain the Customer entity and Purchases association in the return from the linq query.

Use case:

var customers = CustomerService.GetCustomersAndMostRecentOrder();
foreach (Customer c in customers) {
    Console.WriteLine(c.Lastname + ":" + 
                     c.Purchases.Count() == 0 ? "None" : c.Purchases[0].PurchaseOrder);
}

Thanks for your insight.


You will need to do part of the query with linq-to-entities and than the rest with linq-to-objects like so:

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 }
                         } 
                    );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜