DonBoitnott
DonBoitnott

Reputation: 11035

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

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.

Upvotes: 6

Views: 1839

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205799

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();

Upvotes: 10

Related Questions