LINQ查询以检索多级关系数据

Cra*_*g M 4 linq asp.net-mvc

我刚刚开始使用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;

}
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 6

博客有很多帖子.帖子有很多评论.我如何编写LINQ查询以将实体返回到Blog.Posts.Comments级别?

我相信,你可以做到以下几点来实现这个目标:

var blog = (from b in _db.BlogSet.Include("Posts.Comments")
            select b);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,对于每个博客,将提取帖子及其评论.


Dab*_*rnl 5

你可以使用两个语句:

var comments=from post in blog
             from comment in blog.comments
             where comment.PostId==post.Id
             select comment;
Run Code Online (Sandbox Code Playgroud)