Marty
Marty

Reputation: 3555

EF load related collection partially

What I'm trying to achieve is return a list of Categories (in JSON) with the latest (Top 1) modified product in it.

Say I have a Product & Category classes.

Class Category{
   public string Name {get;set;}
   public ICollection<Product> Products {get;set;}
   public Product FirstProduct { get { return          Products.OrderByDescending(p=>p.Modified).FirstOrDefault;}

and a MVC api controller that does the following

....
return db.Categories.Include(p=>p.Products.OrderByDescending(m=>m.Modified).Take(1).FirstOrDefault());
.....

But that doesn't seem to work...

The expected result is something like this (I actually need only the Name and the FirstProduct columns):

[
{Name : "Category1", FirstProduct : {Name : "Product1"}, Products : [{Name: "Product1}]
{Name : "Category2", FirstProduct : {Name : "Product1"}, Products : [{Name: "Product1}]
{Name : "Category3", FirstProduct : {Name : "Product1"}, Products : [{Name: "Product1}]
]

Upvotes: 0

Views: 79

Answers (1)

Slauma
Slauma

Reputation: 177133

A projection might be a solution:

IEnumerable<Category> categories = db.Categories
    .Select(c => new
    {
        Category = c,
        FirstProduct = c.Products
            .OrderByDescending(p => p.Modified)
            .FirstOrDefault()
    })
    .AsEnumerable()
    .Select(x => x.Category);

If you don't need all properties you could project only the needed properties, for example instead of Category = c you would use CategoryName = c.Name or add a Select between OrderByDescending and FirstOrDefault to project properties of Product.

Upvotes: 1

Related Questions