Matt_Bro
Matt_Bro

Reputation: 14472

Get a list of the latest items grouped by a different property in Entity Framework

I have an Entity Framework Entity Shoe that has a one to many relationship with another Entity Person. Each Person has many Shoes. I want to get a list of the latest shoes each person has.

public class Shoe {

  public Long PersonId { get; set; }
  public DateTime PurchaseDate { get; set; }

}

I tried this:

var latestShoesPerPerson = _dbContext.Shoe
    .GroupBy(shoe => shoe.PersonId)
    .Select(shoes => shoes.OrderByDescending(shoe => shoe.PurchaseDate).First());

But, I got this error orderbydescending could not be translated

Upvotes: 0

Views: 36

Answers (1)

Steve Py
Steve Py

Reputation: 34683

The result of a GroupBy is an implicit Key+Collection. It actually has a number of "flavours" to do subtly different things. The one you would be looking for to get the results like that would be GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>)

Using this, the expression would look more like this:

var latestShoesPerPerson = _dbContext.Shoe
    .GroupBy(shoe => shoe.PersonId, (personId, shoes) => shoes.OrderByDescending(s => s.PurchaseDate).FirstOrDefault())
    .ToList(); // list of the earliest shoe for each person.

Upvotes: 1

Related Questions