In entity framework, i know that you can set a property as virtual to get it too lazy load, which is great. But in my service code i would like to load a list of children, and also a list in each of those children.
Instead of getting entity framework to load this data, i can load the data in 2 hits.
Here is an example, of my classes
public class Parent
{
public long Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class Child
{
public long Id { get; set; }
public long ParentId { get; set; }
public ICollection<GrandChild> { get; set; }
}
public class GrandChild
{
public long Id { get; set; }
public long ChildId { get; set; }
public virtual AnotherClass AnotherProperty { get; set; }
}
In my service code i am loading the data like this, as i cant see to be able to load all of them at once (maybe i just dont know the correct query syntax)
var parent = await _context.Parents
.Where(e => e.Id == 9)
.Include(e => e.Children)
.FirstOrDefaultAsync();
var grandchildren = await _context.GrandChildrens
.Where(e => e.Child.ParentId == 9)
.ToListAsync();
// this is load again?
foreach (var child in parent.Children)
child.GrandChildren = (from a in grandChildren where a.ChildId == child.Id).ToList();
Now everytime i am trying to set child.GrandChildren
, entity framework is trying to load the data. How can i stop it loading the data, but without removing the virtual
keyword, as in other instances, i would like entity framework to lazy load.
Also, if anyone knows how to load parent, child, grandchildren in 1 query, please let me know too