我有一个典型的论坛应用程序的最后一个职位,使用嵌套表格: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帮我找到一个主题内的最后一篇文章,请在我的查询内?
谢谢
马克