通过装饰具有属性的属性来排序集合。 (集合检索是通过反射触发)
问题描述:
我有一个对象,其包含一个ICollection
:通过装饰具有属性的属性来排序集合。 (集合检索是通过反射触发)
public abstract class Container : Component, IContainer
{
public virtual ICollection<Component> Components { get; set; }
...
...
}
由于它是虚拟的,所述Component
旨意是延迟装入(“得到”的Component
财产时: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检索数据与订单由指定。这是否有可能?我试图谷歌,如果也许可以用一个属性来装饰该集合属性,该属性将指示EF命令其检索日期。或者我太累了,无法找到好的谷歌查询,或者这是不可能的,或... ...?
PS:禁用该属性的延迟加载不是一个选项,因为该集合中的某些Component
s是它自己的。这会导致大量的选择语句。整个对象结构在理论上可以包含无限深度(现实是 - 现在 - 最多4)
答
据我所知,这是不可能的。
在ObjectContext的API,可以用明确的装载由导航性能,但懒加载创建查询,因为一旦延迟加载启用到集合属性的任何访问必须关闭,立即触发装载这样的明确负载将再次加载数据。即使开启了延迟加载,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
{
...
}
}
...
必须有解决此一劈!也许清理收集并重新填充一个相同的动态代理对象EF的正确排序列表让我们可以工作?明天会给这个镜头..这是有点睡觉的时间在这里:) – TweeZz 2011-05-25 21:05:21
我能够解决它..看到我的答案。 我确实将你的标记标记为正确,因为“不可能”在我的问题上是正确的答案:) 我的回答是,以防万一有人遇到同样的问题。 – TweeZz 2011-05-26 08:36:25
你的答案在哪里? – 2011-05-26 08:51:10