开发者

LINQ to Entities query generating odd error

I have a forum and I'm pulling up a list of recently active topics. I'm ordering the topics either by the last reply date, or in the case of a topic having no replies, then the topic's posted date. The following query works fine:

        var topicsQuery = from x in board.Topics
                          let lastActivityDate = x.Replies.Any()
                        开发者_如何学运维         ? x.Replies.OrderBy(y => y.PostedDate).Last().PostedDate
                                 : x.PostedDate
                          orderby lastActivityDate descending
                          select x;

That query works great. Every time the page loads the topics are ordered correctly. However, now I have an ajax call that looks for updated activity and runs a similar query:

        topics = (from x in DBContext.Topics
                  let lastActivityDate = (x.Replies.Any()
                         ? x.Replies.OrderBy(y => y.PostedDate).Last().PostedDate
                         : x.PostedDate)
                  where x.BoardID == boardID
                  where lastActivityDate > lastTopic.PostedDate
                  orderby lastActivityDate
                  select x).ToList<Topic>();

Can anyone see anything wrong with this LINQ query? It's generating the following error:

LINQ to Entities does not recognize the method 'MyProject.Models.Reply Last[Reply] (System.Collections.Generic.IEnumerable`1[MyProject.Models.Reply])' method, and this method cannot be translated into a store expression.


The reason why it fails is because the entities are not yet loaded and Last() will be called on sql not on the generic list. So first you need to load them up before asking for Last(). The first example might have worked because the board already had a loaded generic list.

Try the following:

topics = (from x in DBContext.Topics.AsEnumerable<Topic>()
                  let lastActivityDate = (x.Replies.Any()
                         ? x.Replies.OrderBy(y => y.PostedDate).Last().PostedDate
                         : x.PostedDate)
                  where x.BoardID == boardID
                  where lastActivityDate > lastTopic.PostedDate
                  orderby lastActivityDate
                  select x).ToList<Topic>();

Refer to: Supported and Unsupported LINQ Methods (LINQ to Entities)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜