How can I access the "ThenInclude() IIncludableQueryable from an Include()

David Thielen 3,211 Reputation points
2023-09-16T17:36:19.3166667+00:00

In Entity Framework, I can set up a query as:

var query = dbContext.Organizations
                     .IncludeAll()
                     .Include(org => org.Events)
                     .ThenInclude(e => e.Signups)

And in this case, what is returned from Include(org => org.Events) is an object that can be used for another Include() call which is an include of the Organizations model. Or it can be a ThenInclude() which is an include of the Events model.

I need to include every Event property. I have a method that does this:

public static IQueryable<Event> IncludeAll(this IQueryable<Event> source)
{
    return source
        .Include(e => e.Description)
        .Include(e => e.Hosts)
        .Include(e => e.Instances)
        .Include(e => e.Interest)
        .Include(e => e.Owner)
        .Include(e => e.Parent)
        .Include(e => e.PatternEvent)
        .Include(e => e.Picture)
        .Include(e => e.Shifts)
        .Include(e => e.Signups)
        .Include(e => e.Tags)
        .Include(e => e.Thumbnail);
}

I think, there must be a way to do the following:

var query = dbContext.Organizations
                    // include all Organization properties
                     .IncludeAll()
                     .Include(org => org.Events)
                    // include all Event properties.
                     .IncludeAll()

And that second IncludeAll() is the IQueryable<Event> IncludeAll and not the IQueryable<Organization> IncludeAll. Or is there a way to define a ThenIncludeAll()?

public static IQueryable<Event> ThenIncludeAll(this IQueryable<Event> source)
{
    return source
        .Include(e => e.Description)
        .Include(e => e.Hosts)
        .Include(e => e.Instances)
        .Include(e => e.Interest)
        .Include(e => e.Owner)
        .Include(e => e.Parent)
        .Include(e => e.PatternEvent)
        .Include(e => e.Picture)
        .Include(e => e.Shifts)
        .Include(e => e.Signups)
        .Include(e => e.Tags)
        .Include(e => e.Thumbnail);
}

Because using a single method to include everything is better than not only having to copy/paste this code everywhere, but update all those code locations when another complex property is added.

Developer technologies .NET Entity Framework Core
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.