开发者

Convert IQueryable<IEnumerable<Entity>> to IQueryable<Entity>

I have the query which return the last UserBattle record for every user:

objectContext.UserBattles.
GroupBy(bu => bu.UserId, bu => bu).
开发者_如何学JAVASelect(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, Single and SingleOrDefault work 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 FirstOrDefault is supported.

That's the case for the .NET Provider for SQL Server. If your query even doesn't work with FirstOrDefault then it's most likely a limitation of the MySQL .NET Connector (by design or as a bug?).

Just to mention for completeness: Last and LastOrDefault are 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 as gbu => gbu.OrderByDescending(bu => bu.DateTime).FirstOrDefault(). The logical identical expression gbu => gbu.OrderBy(bu => bu.DateTime).LastOrDefault() is possible in LINQ to Objects but not in LINQ to Entities.


try .SingleOrDefault(), that the method for what you want

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜