Eagerly/explicitly load "child" entities with only navigation property to "parent"

515 views Asked by At

I have an EF Core 2.1 Code First model with a "parent-child" type relationship between two classes:

class Parent
{
    public int Id {get; set;}
    public string Name {get; set;}
}

class Child
{
    public int Id {get; set;}
    public string Description { get; set; }
    public Parent Parent { get; set; }
}

I want to load a certain Parent, and make sure that all its Child entities are loaded too. However, there is no navigation property to Child, and I cannot modify the classes, so I can't add one.

dbContext.Parents
    .Include(p => p.???)
    .Find(1);

I suppose I could do a second query where I look everything up in reverse:

dbContext.Children.Where(c => c.Parent.Id == loadedParent.Id)

but that does not seem very efficient, especially when you load multiple parents and do something horrible like this:

var parentIds = loadedParents.Select(p => p.Id);
var children = dbContext.Children.Where(c => parentIds.Contains(c.Parent.Id));

Is there a way to make sure entities are loaded when you only have a "child-to-parent" navigation property?

1

There are 1 answers

4
Gert Arnold On BEST ANSWER

make sure that all its Child entities are loaded too

So load the Child entities:

var children = dbContext.Children.Include(c => c.Parent)
    .Where(c => c.Parent.Id == 1).ToList();

Or use wider selection criteria than c.Parent.Id == 1 if you want to get multiple parents.

If necessary you can list the loaded parents by accessing the Local collection:

va parents = dbContext.Parents.Local;