Entities:
public class User
{
public long Id { get; }
public ICollection<File> Files { get; }
}
public class File
{
public long Id { get; }
public DateTime CreatedAt { get; }
public string Name { get; }
public User? User { get; } // nullable for other reasons
}
I want the name of the latest file for each user. I tried:
var data = await context
Files
.Where(x => x.User != null)
.GroupBy(x => x.User!.Id)
.Select(x => x.MaxBy(y => y.CreatedAt)!)
.ToDictionaryAsync(k => k.User.Id, v => v.Name);
But that throws
The LINQ expression ... could not be translated
I assume MaxBy
is unsupported (in EF Core 8).
Is there a workaround?
Thanks to the comment by @PanagiotisKanavos above, the simplest solution is:
await context
.Users
.Include(x => x.Files)
.Where(x => x.Files.Any())
.ToDictionaryAsync(
x => x.Id,
x => x.Files.OrderByDescending(y => y.CreatedAt).First().Name)
That completely avoids the MaxBy
issue.
Vote here for them to support it.