在实体上显式加载多个引用/集合 [英] Explicit loading of multiple references/collections on entity

查看:126
本文介绍了在实体上显式加载多个引用/集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下实体模型:

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

在我的代码中,我加载了 / code>实体:

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

但这会导致两个DB查询。

But this results in two DB queries.

问题:是否有更优雅的方式,这将允许在单个查询中显式加载多个导航属性?

如果我没有加载 parent ,我会热切加载:

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).

推荐答案

唯一可能的方法是(afaik)重新加载父属性。假设变量 parent 附加到上下文中:

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).

这篇关于在实体上显式加载多个引用/集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆