Entity Framework – Is there a way to automatically eager-load child entities without Include()?

No you cannot do that in mapping. Typical workaround is simple extension method:

public static IQueryable<Car> BuildCar(this IQueryable<Car> query) {
     return query.Include(x => x.Wheels)
                 .Include(x => x.Doors)
                 .Include(x => x.Engine)
                 .Include(x => x.Bumper)
                 .Include(x => x.Windows);
}

Now every time you want to query Car with all relations you will just do:

var query = from car in db.Cars.BuildCar()
            where car.Make == "Ford"
            select car;

Edit:

You cannot nest calls that way. Include works on the core entity you are working with – that entity defines shape of the query so after you call Include(x => Wheels) you are still working with IQueryable<Car> and you cannot call extension method for IQueryable<Engine>. You must again start with Car:

public static IQueryable<Car> BuildCarWheels(this IQuerable<Car> query) {
    // This also answers how to eager load nested collections 
    // Btw. only Select is supported - you cannot use Where, OrderBy or anything else
    return query.Include(x => x.Wheels.Select(y => y.Rim))
                .Include(x => x.Wheels.Select(y => y.Tire));
}

and you will use that method this way:

public static IQueryable<Car> BuildCar(this IQueryable<Car> query) {
     return query.BuildCarWheels()
                 .Include(x => x.Doors)
                 .Include(x => x.Engine)
                 .Include(x => x.Bumper)
                 .Include(x => x.Windows);
}

The usage does not call Include(x => x.Wheels) because it should be added automatically when you request eager loading of its nested entities.

Beware of complex queries produced by such complex eager loading structures. It may result in very poor performance and a lot of duplicate data transferred from the database.

Leave a Comment