2013-06-18 25 views
1

我有一個典型的論壇應用程序的最後一個職位,使用嵌套表格:ASP.Net MVC C#檢索父子子表

論壇=>主題=>郵政(S)

我「M嘗試使用LINQ來填充視圖模型來顯示一個帖子最後海報,一個主題,一個論壇內 - 但是,當我運行查詢,我得到的錯誤:

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

我知道它在這條線上

LastPost = f.Topics.FirstOrDefault().Posts.LastOrDefault().Author

我的控制器:

public ActionResult Index() 
    { 
     var forum = db.Fora.Include(x => x.Topics) 
      .Select(f => new ForumViewModel 
      { 
       ForumId =f.ForumId, 
       Title=f.Title, 
       Description=f.Description, 
       Topics=f.Topics.Count(), 
       Posts=f.Topics.FirstOrDefault().Posts.Count(), 
       LastPost = f.Topics.FirstOrDefault().Posts.LastOrDefault().Author 
      } 
      ).ToList(); 

     return View(forum); 
    } 

我的模型是:

namespace centreforum.Models 
{ 
public class Forum 
{ 
    public int ForumId { get; set; } 
    public string Title { get; set; } 
    public string Description { get; set; } 
    public List<Topic> Topics { get; set; } 
} 

public class Topic 
{ 
    public int TopicId { get; set; } 
    public int ForumId { get; set; } 
    public string Title { get; set; } 
    public string Content { get; set; } 
    public string Author { get; set; } 
    public string DateOfPost { get; set; } 
    public int Views { get; set; } 
    public Forum Forum { get; set; } 
    public List<Post> Posts { get; set; } 
} 

public class Post 
{ 
    public int PostId { get; set; } 
    public int TopicId { get; set; } 
    public string Title { get; set; } 
    public string Content { get; set; } 
    public string Author { get; set; } 
    public string DateOfPost { get; set; } 
    public int MyProperty { get; set; } 
    public Topic Topic { get; set; } 
} 
} 

...和我的視圖模型爲:

namespace centreforum.Models 
{ 
public class ForumViewModel 
{ 
     public int ForumId { get; set; } 
     public string Title { get; set; } 
     public string Description { get; set; } 
     public int Topics { get; set; } 
     public int Posts { get; set; } 
     public string LastPost { get; set; } 
} 
} 

在查詢中可以yone幫我找到一個主題內的最後一篇文章,請在我的查詢內?

謝謝

馬克

回答

4
LastPost = f.Topics.FirstOrDefault().Posts.OrderBy(c => c.CreatedAt).LastOrDefault().Author 

我認爲,如果你通過一個給定的標準命令你的帖子,例如createdat,應該按預期工作。