LINQ query to retrieve multiple levels of relational data

I'm just speeding up with asp.net mvc, and I'm wondering how one could get relational data to a depth of more than one level from the object specified in the from clause. As an example, you can use the following domain model:

There are a lot of blog posts. Posts have many comments.

How do I write a LINQ query to return entities to the Blog.Posts.Comments level?

The only (not very elegant) solution I came across was to use the LINQ query to get the blog and posts, and then to get comments.

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; } 
+4
source share
2 answers

There are a lot of blog posts. Posts have many comments. How to write a LINQ query to return entities to the Blog.Posts.Comments level?

I believe you could do the following to achieve this:

 var blog = (from b in _db.BlogSet.Include("Posts.Comments") select b); 

In this case, posts and their comments will be added for each blog.

Mark

+6
source

You can simply use two of the operators:

 var comments=from post in blog from comment in blog.comments where comment.PostId==post.Id select comment; 
+5
source

All Articles