LINQ到实体查询产生错误奇 [英] LINQ to Entities query generating odd error

查看:127
本文介绍了LINQ到实体查询产生错误奇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个论坛,我拉起最近活跃的主题列表。我订购的主题无论是最后回复日期或话题的情况下,有没有回复,那么主题的发布时间。下面的查询工作正常:

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;

这查询的伟大工程。每次页面加载时间主题正确排序。不过,现在我有一个Ajax调用,以查找更新活动,并运行一个类似的查询:

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>();



任何人都可以看到什么不对的LINQ查询?它产生了以下错误:

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

LINQ到实体无法识别方法MyProject.Models.Reply尾页[回复](System.Collections.Generic.IEnumerable`1 [ MyProject.Models.Reply])的方法,而这种方法不能被翻译成店的表情。

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.

推荐答案

之所以说它失败是因为实体尚未加载和Last()将SQL不是泛型列表上调用。因此,首先你需要询问上次之前加载它们()。 。第一个例子可能已经工作,因为在已经有一个装泛型列表

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.

尝试以下操作:

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>();



参考:的支持和不支持LINQ方法(LINQ到实体)

这篇关于LINQ到实体查询产生错误奇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆