繁体   English   中英

ASP.Net MVC C#检索父子子表的最后一篇文章

[英]ASP.Net MVC C# retrieving the last post of a parent child child table

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

论坛=>主题=>帖子

我正在尝试使用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; }
}
}

任何人都可以帮我找一个主题中的最后一篇文章,在我的查询中吗?

谢谢,

标记

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

我认为,如果您按照给定的标准订购帖子,例如createdat,它应该按预期工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM