我的方案是我有一个对象 FOO
,其上有一个 virtual List<bar>
属性 . 这是由EF自动生成的 .
在我加载 FOO
我处理数据上下文后,我通过DTO将 FOO
转换为业务对象 . 例如
var newFOO = FOO_Dto.change(FOO);
在 FOO_Dto.change
内部我想检查虚拟列表属性是否为空/空 . I understand that closing the ObjectContext and checking the navigation property will throw an error . 在我的数据层中,有时我会返回列表中的 FOO
和没有列表的 FOO
.
我的问题是如何检查导航属性以查看列表是否已填充,并避免当前生成的ObjectContext错误
非常感谢你!!
EDIT
在评论部分,我特意希望关闭上下文,然后检查是否加载了 List<Bar>
属性 .
1 回答
不,您可以't, other than the ugly way of trying and catching the exception. You can only determine whether a collection is loaded by getting the owner' s
DbEntityEntry
,您只能通过上下文实例获取 .但是如果您事先知道集合可能在上下文范围之外被解决,则需要在上下文处于活动状态时加载它,或者不加载它并防止延迟加载 . 永远不要允许延迟加载在上下文的生命周期之外发生 .
在大多数情况下,这意味着您必须关闭延迟加载并急切地加载使用方法所需的所有数据 .
我以不连贯的方式使用EF越多,我就越少允许延迟加载 . 我接近考虑延迟加载反模式 .