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!

Mark Chidlow
  • 1,432
  • 2
  • 24
  • 43

1 Answers1

-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

Sharpman
  • 9
  • 1
  • 3
  • 1
    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. – Mark Chidlow Dec 12 '16 at 11:56