AJ.
AJ.

Reputation: 1671

How can I load multiple levels when lazy loading in EF Core?

I have a program using C# / WPF and SQL Server with EF Core 5. Sometimes I use eager loading, for example:

(from r in MyContext.Refractions where r.Id == id select r)
    .Include(r => r.RightLens)
    .ThenInclude(l => l.Prisms);

and so on. This is a database of optical data, hence the field names. Refractions are linked to (eye) Examinations.

When I want to lazy load, I use the following:

MyContext.Entry(patient)
         .Collection(e => e.Examinations).Load();

My question is, when using the second, lazy option, is there a way to also load associated data (the equivalent of .Include for the Load method)?

So for example, I want the equivalent of:

MyContext.Entry(patient)
         .Collection(e => e.Examinations)
         .Load().Include(r => r.Refractions);

or do I need to detect that the Refractions collection is not loaded somewhere in my view model and then load it manually when required?

Upvotes: 2

Views: 621

Answers (1)

Mr.Deer
Mr.Deer

Reputation: 476

As I don't think this is possible yet, you could write some methods like those:

public IEagerLoadedQueryable<E, P> LoadRelated<E, P>(IQueryable<E> query, Expression<Func<E, P>> navProperty) where E : class {
  var q= query.Include(navProperty);
  return new EagerLoadedQueryable<E, P>(q);
}

public IEagerLoadedQueryable<E, Prop> ThenLoadRelated<E, Prev, Prop>(IEagerLoadedQueryable<E, IEnumerable<Prev>> query, Expression<Func<Prev, Prop>> navProperty) where E : class {
  var q= (IIncludableQueryable<E, IEnumerable<Prev>>)query;
  return new EagerLoadedQueryable<E, Prop>(q.ThenInclude(navProperty));
}


public IEagerLoadedQueryable<E, Prop> ThenLoadRelated<E, Prev, Prop>(IEagerLoadedQueryable<E, Prev> query, Expression<Func<Prev, Prop>> navProperty) where E : class {
  var q= (IIncludableQueryable<E, Prev>)query;
  return new EagerLoadedQueryable<E, Prop>(q.ThenInclude(navProperty));
}

Upvotes: 1

Related Questions