【问题标题】:EF5 & Detached POCO with navigational property returning nullEF5 & Detached POCO,导航属性返回 null
【发布时间】:2012-11-01 10:47:25
【问题描述】:

我有一个问题,我相信可以通过简单的理解来解决。我正在使用带有代码优先和 POCO 的 Entity Framework 5。我为我的所有 POCO 对象正确配置了所有导航属性(虚拟)。当我查询一个对象(PO​​CO)然后返回该 POCO 作为结果时,就会出现问题。 POCO 的所有导航属性都为空:

class PocoParent  { // all of these are properties (get/set)
    public int Id;
    public string ParentProperty;
    public virtual PocoChild NavProperty;
}
class PocoChild {
    public int Id;
    public int ParentId;
    public string Name;
    public virtual PocoParent Parent;
}

在处理我的查询的存储库类中:

IEnumerable<PocoChildren> GetAllChildrenFor(int parentId) {
    using(Context db = new Context()) {
        var pcs = db.PocoParents.Where(p => p.Id == parentId);
        return pcs;
    }
}

现在使用存储库:

...
var children = repo.GetAllChildrenFor(queriedParent.Id);
...

现在使用存储库中的结果,这是发生错误的地方:

...
foreach(child in children) {
   if(child.Parent.NavProperty == "null") {  !!! Exception: child.Parent ObjectContext already disposed
   }
}
...

如何处置 ObjectContext(分离 POCO 对象),但至少保留一级导航属性?我一直在寻找解决方案,但我很困惑,因为解决方案在如何做到这一点上相互冲突。

--- 回顾 ---- 有了下面给出的答案,如果我要将存储库中的查询更改为以下内容:

IEnumerable<PocoChildren> GetAllChildrenFor(int parentId) {
    using(Context db = new Context()) {

        var pcs = db.PocoParents.Include(p => p.Select(prop => prop.Parent).Where(p => p.Id == parentId);

        return pcs;
    }
}

是否会返回所有实体,它们将包含一个非空的 .Parent 属性,或者我指定的任何属性?

【问题讨论】:

    标签: c# repository-pattern poco entity-framework-5


    【解决方案1】:

    默认情况下启用延迟加载,这就是可导航属性为空的原因。延迟加载意味着可导航属性在被请求之前不会加载。如果在请求它们时上下文消失了,它们会被设置为 null,因为它们无法加载。

    要解决这个问题,您需要禁用延迟加载或显式(并且急切地)加载您需要的属性。

    这个MSDN magazine article 是一个很好的来源,可以帮助您确定最适合您的路线。

    【讨论】:

    • 谢谢,我想我现在明白了。如果您不介意验证它,我在底部重述了我的问题以供评估。
    • 我在使用 lambda 版本的 Include 时总是运气不佳。所以我会把它写成:...Include("Parent").Where...否则,是的,我想你已经明白了。
    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    相关资源
    最近更新 更多