Is it possible to load nested navigation properties using EntityEntry.Reference?

c# entity-framework-core

Question

Take these example classes:

class TemplatePart
{
    public PartStock stock {get; set;}
    ...other POCOs
}

class PartStock
{
    public Part part {get; set;}
    ...other POCOs
}

class Part
{
    public PartName name {get; set;}
    ...other POCOs
}

Now, suppose I already have an entity for a TemplatePart. I can do this:

var entry = context.Entry(templatePart);
entry.Reference(x => x.PartStock).Load();

That would load the navigation property for the PartStock. But how do I do this:

entry.Reference(x => x.PartStock.Part).Load();

That produces an exception:

The expression 'x => x.PartStock.Part' is not a valid property expression. The expression should represent a simple property access: 't => t.MyProperty'. Parameter name: propertyAccessExpression

Is there some alternative to this that still uses the entry I already have? I don't want to have to reload the whole thing again using Include if I don't have to.

I am using EntityFramework Core 2.

1
2
2/13/2019 4:52:09 PM

Accepted Answer

Instead of directly calling Load method, you could use a combination of Query(), Include / ThenInclude and Load methods:

entry.Reference(x => x.PartStock)
    .Query()
    .Include(x => x.Part)
    .Load();
5
2/13/2019 4:52:36 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow