Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 425
DonBoitnott Avatar asked Feb 13 '19 16:02

DonBoitnott


People also ask

What are the way of loading data in Entity Framework?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

What is the use of navigation properties in Entity Framework?

A navigation property is an optional property on an entity type that allows for navigation from one end of an association to the other end. Unlike other properties, navigation properties do not carry data. A navigation property definition includes the following: A name.

How do I set eager loading in Entity Framework?

Entity Framework : A Comprehensive Course Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by the use of the Include method. It means that requesting related data be returned along with query results from the database.

What is .include in Entity Framework?

Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.


1 Answers

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();
like image 141
Ivan Stoev Avatar answered Oct 23 '22 12:10

Ivan Stoev