I have the query which return the last UserBattle record for every user:
objectContext.UserBattles.
GroupBy(bu => bu.UserId, bu => bu).
Select(gbu => gbu.OrderByDescending(bu => bu.DateTime).First());
Unfortunately it doesn’t work (at least MySQL .NET Connector provider can’t convert First to SQL). As alternative I can replace First call by Take(1). But unfortunately in this case the result will be IQueryable<IEnumerable<UserBattle>> instead of IQueryable<UserBattle>. Is there any way to get IQueryable<UserBattle> without going to LINQ To Objects (for example, SelectMany would solve my problem).
First,FirstOrDefault,SingleandSingleOrDefaultwork all as the finishing method of a LINQ to Entities query (as “greedy” operators at the end which cause the query to execute).However in a projection (Select(…)) only
FirstOrDefaultis supported.That’s the case for the .NET Provider for SQL Server. If your query even doesn’t work with
FirstOrDefaultthen it’s most likely a limitation of the MySQL .NET Connector (by design or as a bug?).Just to mention for completeness:
LastandLastOrDefaultare not supported at all in LINQ to Entities, neither as finishing methods nor in a projection. That’s the reason why your Select expression must be written asgbu => gbu.OrderByDescending(bu => bu.DateTime).FirstOrDefault(). The logical identical expressiongbu => gbu.OrderBy(bu => bu.DateTime).LastOrDefault()is possible in LINQ to Objects but not in LINQ to Entities.