LINQ to Entities: Get more recent date from each group

I'm trying to group Reports by Type and return the most recent Created date for each Report Type, using LINQ to Entities. I did my research and read lots of questions and most of them are solved using a similar query than mine:

var query = ctx.DataWorkspace.ApplicationData.Reports
         .GroupBy(i => i.ReportType)
         .Select(i => new { name = i.Key, y = i.Max(h => h.DateCreated) });

But I get this error:

A query cannot return non-Entity types that contain embedded entities

What am I doing wrong? Is it because it's LINQ-to-Entities?

Upvotes: 0

Views: 73

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Error message is quite descriptive. Your anonymous type contains a property which is typed as an entity (name = i.Key part). You can't do that, because LINQ to Entities would not be able to track changes to these entities.

You can take just some of the properties from ReportType instead of entire entity:

var query = ctx.DataWorkspace.ApplicationData.Reports
     .GroupBy(i => i.ReportType)
     .Select(i => new { name = i.Key.Name, y = i.Max(h => h.DateCreated) });

i.Key.Name is just an example. Your entity probably has different property/properties you care about.

Upvotes: 1

Related Questions