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

走远了吗. 提交于 2021-02-07 18:25:42

问题


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:


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


来源:https://stackoverflow.com/questions/54675380/is-it-possible-to-load-nested-navigation-properties-using-entityentry-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!