问题描述
|
我有一个包含
ICollection
的对象:
public abstract class Container : Component,IContainer
{
public virtual ICollection<Component> Components { get; set; }
...
...
}
由于它是虚拟的,因此ѭ2将被延迟加载(当“获取”ѭ2的属性:myContainerInstance.Components
时)。
我们的应用程序严重依赖反射。反射部分之一是检索某个Container的所有属性,循环遍历并获取每个属性的值。像这样:
var props = type.GetProps();
foreach (var prop in props)
{
var propValue = prop.GetValue(bo,null); // EF triggers lazy loading in case the prop is a virtual ICollection and immediately _materializes_ all the data
...
...
}
我试图找到一种方法,使EF通过指定的顺序检索数据。有可能吗?我正在尝试使用google搜索,是否有可能用指示EF命令其检索日期的属性装饰该collection属性。还是我太累了,找不到合适的Google查询,或者不可能,或者...?
PS:禁用该属性的延迟加载不是一种选择,因为该集合中的某些ѭ2本身就是ѭ7。这导致巨大的选择语句。理论上,整个对象结构可以包含一个无限的深度(现实-到目前为止-最多为4)
解决方法
据我所知,这是不可能的。
在ObjectContext API中,可以通过从导航属性创建查询来进行显式加载,但是必须禁用延迟加载,因为一旦启用了延迟加载,对collection属性的任何访问都会立即触发加载,因此显式加载将再次加载数据。即使启用了延迟加载,DbContext API也应该能够使用显式加载。仍然显式加载意味着必须手动调用某些方法/查询才能加载属性。
,这是我最后做的事情(简化版):
var propValue = prop.GetValue(bo,null); // this (in case the `prop` is a virtual `ICollection<Component>`) lazy loads all components,returning them not always in the same order (due to paralelism on sql server?))
if (prop.PropertyType.IsGenericType)
{
...
if (prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
...
}
else if (innerType.IsSubclassOfOrEquivalentTo(typeof(Component)) && propValue != null)
{
// order the list of components in memory into a new variable
var listOfComponents = ((IEnumerable) propValue).Cast<Component>().OrderBy(c => c.ComponentId);
dynamic componentsHash = propValue; // I had to use dynamic,because sometimes the propValue was an List<...>,sometimes a HashSet<...>,sometimes a ...
componentsHash.Clear(); // empty the collection retrieved by EF
int componentCount = listOfComponents.Count;
for (var i = 0; i < componentCount; i++)
{
var component = listOfComponents[i];
componentsHash.Add(component); // re-add components to the collection
...
}
// at this point the collection object contains ordered dynamic proxy objects (attached EF objects)
}
else
{
...
}
}
...