我有一个典型的论坛应用程序,使用嵌套表:
论坛 => 主题 => 帖子
我正在尝试使用 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; }
}
}
谁能帮我找到一个主题中的最后一篇文章,请在我的查询中?
谢谢,
标记