2011-01-09 45 views
1

我有一個論壇,我拉起最近活躍的主題列表。我在最後一個回覆日期前訂購主題,或者在沒有回覆的主題的情況下,然後是主題的發佈日期。以下查詢工作正常:LINQ to Entities查詢生成奇怪的錯誤

 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調用,以查找更新活動,並運行一個類似的查詢:

 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查詢?它生成以下錯誤:

LINQ to Entities無法識別方法'MyProject.Models.Reply Last [Reply](System.Collections.Generic.IEnumerable`1 [MyProject.Models.Reply])''方法,並且此方法不能轉換爲商店表達式。

回答

1

它失敗的原因是因爲實體尚未加載,Last()將在sql上調用而不是在通用列表上。所以首先你需要在請求Last()之前加載它們。第一個例子可能已經工作,因爲已經有一個加載的通用列表。

嘗試以下操作:

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

參考:Supported and Unsupported LINQ Methods (LINQ to Entities)

+0

我不能看到OP的版本有什麼區別,你可以突出不同? – 2011-01-09 06:39:36