gpt4 book ai didi

c# - EF5 和分离式 POCO,导航属性返回 null

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:28 26 4
gpt4 key购买 nike

我遇到了一个我认为可以通过简单理解来解决的问题。我正在使用代码优先和 POCO 的 Entity Framework 5。我已为所有 POCO 对象正确配置(虚拟)所有导航属性。当我查询对象 (POCO) 然后返回该 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 属性,或者我指定的任何属性?

最佳答案

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

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

MSDN magazine article是一个很好的资源,可以帮助您决定哪条路线最适合您。

关于c# - EF5 和分离式 POCO,导航属性返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13353419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com