2011-05-25 57 views
0

我有一個對象,其包含一個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)

回答

0

據我所知,這是不可能的。

在ObjectContext的API,可以用明確的裝載由導航性能,但懶加載創建查詢,因爲一旦延遲加載啓用到集合屬性的任何訪問必須關閉,立即觸發裝載這樣的明確負載將再次加載數據。即使開啓了延遲加載,DbContext API也應該能夠使用顯式加載。仍然顯式加載意味着你必須手動調用一些方法/查詢來加載屬性。

+0

必須有解決此一劈!也許清理收集並重新填充一個相同的動態代理對象EF的正確排序列表讓我們可以工作?明天會給這個鏡頭..這是有點睡覺的時間在這裏:) – TweeZz 2011-05-25 21:05:21

+0

我能夠解決它..看到我的答案。 我確實將你的標記標記爲正確,因爲「不可能」在我的問題上是正確的答案:) 我的回答是,以防萬一有人遇到同樣的問題。 – TweeZz 2011-05-26 08:36:25

+0

你的答案在哪裏? – 2011-05-26 08:51:10

0

這是我最後還是沒買(簡體版):

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 
    { 
     ... 
    } 
} 
... 
相關問題