2

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?

1

1 Answer 1

1

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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.