1

How do you filter the nested includes in an EF Linq query? For example if I have:

var blogs = context.Blogs
.Include(blog => blog.Posts)
    .ThenInclude(post => post.Author)
    .ThenInclude(author => author.Photo)
.ToList();

But I only want to get Blogs with Posts after a certain date, or Authors by the name 'Mark'.

I would like to be able to do the following in some way:

var blogs = context.Blogs
.Include(blog => blog.Posts).Where(... blog.Posts.Date>X.... )
    .ThenInclude(post => post.Author).Where(... post.Author.Name=='Mark' ...)
    .ThenInclude(author => author.Photo)
.ToList();

Or am I missing something really simple here? Thanks for your advice in advance!

2
  • 2
    Is LazyLoading disabled? I'm quite sure you can do something like .Include(blog => blog.Posts.Where(yourCondition)) Commented Dec 12, 2016 at 11:06
  • Thanks Alex - yes this is a duplicate - apologies all! Commented Dec 12, 2016 at 11:58

1 Answer 1

-2

The EF allows what you are requesting with no additional work

var blogs = context.Blogs
.Include(blog => blog.Posts).Where(b => b.Posts.Date>X)
    .Include(post => post.Author).Where(p => p.Author.Name=='Mark')
    .Include(author => author.Photo)
.ToList();

The EF will create the actual query only when the ToList() is called, thus constructing an efficient query.

See https://msdn.microsoft.com/en-us/library/bb738633(v=vs.110).aspx

Sign up to request clarification or add additional context in comments.

1 Comment

This won't compile as Author is a property of a Post, hence the need for ThenInclude(). In your example compiler is expecting Author is a property of a Blog.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.