我刚刚开始使用 asp.net mvc,我想知道如何从 from 子句中指定的实体获取超过一层深度的关系数据。使用以下域模型作为示例:
一个博客有很多帖子。帖子有很多评论。
我将如何编写 LINQ 查询以将实体返回到 Blog.Posts.Comments 级别?
我想出的唯一(不太优雅)的解决方案是使用 LINQ 查询来获取博客和帖子,然后使用 foreach 来获取评论。
var blog = (from b in _db.BlogSet.Include("Posts")
select b);
foreach (Post p in blog.Posts)
{
var comments = (from c in _db.CommentSet
where c.PostId = p.Id
select c);
p.Comments = comments;
}
最佳答案
A Blog has many posts. Posts have many comments. How would I write a LINQ query to return entities down to the Blog.Posts.Comments level?
我相信,您可以执行以下操作来实现这一目标:var blog = (from b in _db.BlogSet.Include("Posts.Comments") select b);
在这种情况下,对于每个博客,将获取帖子及其评论。
马克
关于asp.net-mvc - 用于检索多级关系数据的 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1276066/