EF Core Collection Load .. of a Collection
Asked Answered
E

1

17

Using EF Core 1.1.0

I have a model that has collections that themselves have collections.

public class A {  
  public string Ay {get;set;}    
  public List<B> Bees {get;set;}
}

public class B {
  public string Be {get;set;}
  public List<C> Seas {get;set;}
}

public class C {
  public string See {get;set;}
  public bool InDark {get;set;}
  public List<D> Sigh {get;set;}
}

Now.. A is huge, and 99% of the time I don't care about B, so it doesn't get loaded. If I did load it, then it would be something like:

context.A.Include(a=>a.Bees).ThenInclude(b=>b.Seas).ThenInclude(c=>c.Sigh)...

Now let's say I already have A loaded up and the 1% happens for me to care about B. We don't have lazy loading yet, but the last release did give us explicit loading. Awesome.

context.Entry(A).Collection(a=>a.Bees).Load();

Problem seems to be that there isn't a way to include the additional collections inside B? Do I have no choice but to reload A with the .Include.ThenInclude.ThenInclude.Etc?

Encarnacion answered 8/1, 2017 at 3:12 Comment(1)
You can create an instance of Queryable<TEntity> and then add invocations for Include and ThenInclude before to call ToList method, have you tried that?Familial
C
25

Fortunately you have an option. Instead of directly calling Load, you can use Query method and apply as many Include / ThenInclude as you wish.

For your sample, it would be something like this:

context.Entry(A).Collection(a => a.Bees)
    .Query()
    .Include(b => b.Seas).ThenInclude(c => c.Sigh)...
    .Load();
Contractile answered 8/1, 2017 at 16:54 Comment(5)
I had actually forgotten this, thanks for reminding me :) It also worked in EF6.Hupp
Thank you.. this did the trick. I was hoping they'd get lazy loading done sooner than later but in the interim, this sort of thing lets me make my own lazy-ish patterns in my repository.Encarnacion
Hi @Gert, no way you could forget something :) Cheers and HNY!Contractile
Does this not work with lazy-loading proxies, or maybe just EF Core 3 in general? If I do this it says the collection isn't loaded. Only says it's loaded if I omit everything between .Collection(...) and .Load(): i.imgur.com/2GSQQ26.pngJoker
@Joker With lazy loading - probably not. For other methods of loading related data - yes, it works, the IsLoaded flag is not used by them, same for EFC5 filtered includes, which allow you to load just few records, and then is it loaded or not? Apparently not. So basically you should not rely on that flag, And lazy loading should be avoided in general due to so many side effects and unexpected behaviors.Contractile

© 2022 - 2024 — McMap. All rights reserved.