我有一个典型的论坛应用程序,使用嵌套表格:
论坛 => 主题 => 帖子
我正在尝试使用 LINQ 填充 ViewModel 以显示论坛中主题中帖子的最后张贴者 - 但是,当我运行查询时,出现错误:
LINQ to Entities 无法识别 'centreforum.Models.Post LastOrDefault[Post](System.Collections.Generic.IEnumerable 1[centreforum.Models.Post]) 方法,并且此方法无法转换为存储表达式
我知道它在查询中的这一行:
LastPost = f.Topics.FirstOrDefault().Posts.LastOrDefault().Author
我的 Controller 是:
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
我认为,如果您按给定条件(例如创建时间)对您的帖子进行排序,它应该会按预期工作。
关于c# - ASP.Net MVC C# 检索父子子表的最后一篇文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17169389/