1

我有一个典型的论坛应用程序,使用嵌套表:

论坛 => 主题 => 帖子

我正在尝试使用 LINQ 填充 ViewModel 以在论坛内的主题中显示帖子的最后一张海报 - 但是,当我运行查询时,出现错误:

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; }
}
}

...我的 ViewModel 是:

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; }
}
}

谁能帮我找到一个主题中的最后一篇文章,请在我的查询中?

谢谢,

标记

4

1 回答 1

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

我认为,如果您按照给定的标准(例如 createdat)对帖子进行排序,它应该可以按预期工作。

于 2013-06-18T12:58:58.787 回答