Relatude Help

24 Eager loading: Include and Preload

Include and Preload load related nodes with the result, in the same round trip. Use Include for relations and Preload for Reference<T> and References<T> properties, which yield nothing from foreach unless preloaded. Without them, each relation you read costs a trip to the store.

var events = db.Query<IEvent>()
               .Include(e => e.Venue)
               .Include(e => e.Attendees, top: 50)      // at most 50 attendees per event
               .Preload(e => e.Cover)
               .Execute();

foreach (var e in events) {
    var venue = e.Venue.Get();                  // already loaded
    foreach (var a in e.Attendees) { … }        // already loaded
    foreach (var img in e.Cover) { … }          // yields, because it was preloaded
}
  • Going deeper: ThenInclude / ThenPreload — ThenInclude and ThenPreload load the next level, from the nodes the previous Include loaded. When that Include names a relation end, give it the related node type, so the next level knows what it starts from:
  • Filtering what gets included — Each of these methods also takes a filter on the related nodes. The filter applies before top, and it never changes the main result, only what is loaded:
  • When you only need ids — SelectId() returns the ids without loading the nodes: