Explicit loading of multiple references/collections on entity

孤人 提交于 2019-12-14 03:46:39

问题


Consider following entity model:

public class Parent
{
    public virtual FirstChild FirstChild { get; set; }
    public virtual SecondChild SecondChild { get; set; }
}

In my code, I have loaded Parent entity:

Parent parent = <loaded in some way>;

To explicitly load its navigational properties, I use

db.Entry(parent).Reference(p => p.FirstChild).Load();
db.Entry(parent).Reference(p => p.SecondChild).Load();

But this results in two DB queries.

Question: is there a more elegant way, that would allow to explicitly load more than one navigational property in single query?

If I didn't have parent loaded, I would do eager loading:

Parent parent = db.Parents
    .Include(p => p.FirstChild)
    .Include(p => p.SecondChild)
    .FirstOrDefault();

but, as I mentioned, I already have it loaded without related entities (and I can't modify the loading code).


回答1:


The only possible way (afaik) is to reload the parent property. Assuming the variable parent is attached to the context:

var tmp = db.Parents
    .Include(p => p.FirstChild)
    .Include(p => p.SecondChild)
    .FirstOrDefault(p => p.Equals(parent));

// tmp and parent are the same instance now!
var isTrue = ReferenceEquals(tmp, parent);

var child1 = parent.FirstChild;  // is already loaded
var child2 = parent.SecondChild; // is already loaded

This works, because the context will detect that entity you are looking for is loaded and attached already and therefore not create a new one but rather update the old one (parent in this case).



来源:https://stackoverflow.com/questions/29013963/explicit-loading-of-multiple-references-collections-on-entity

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