2013-02-15 28 views
0

介紹

MemberAccess LINQ表達

比方說,我有這些類:C#樓子屬性使用導航串

public class Door { 
    public string Label { get; set; } 
} 

public class House { 
    public string Address { get; set; } 
    public Door FrontDoor { get; set; } 
} 

現在,這些都在數據庫中,抽象簡單的模型使用實體框架4。因此,當我需要做的House有序列表然後我可以使用:

dbObjectContext.Houses.OrderBy(h=>h.Name); 

然後,如果我想FrontDoor.Label訂購,我可以使用:

dbObjectContext.Houses.OrderBy(h=>h.FrontDoor.Label); 

問題

我打算是旨在由WPF數據網格將顯示房屋的列表中使用的分選方法。該方法的簽名是象下面這樣:

IOrderedQueryable<TEntity> ApplySortingToQuery<TEntity>(bool ascending 
    ,IQueryable<TEntity> finderQuery,string propertyPath) 

我想用對象類型TEntity的知識和屬性訪問路徑字符串propertyPath打造排序依據表達。

在DataGrid中,要排序的對象是House型的,它的列是地址前門標籤。現在,DataGrid中的地址列已將SortMemberPath設置爲Address。而前門標籤列的是FrontDoor.Label

在開始的時候,我可以只使用if-else來確定使用什麼排序依據表達,例如:

if (col.SortMemberPath=="Address") { 
    query=query.OrderBy(h=>h.Address); 
} else if (col.SortMemberPath=="FrontDoor.Label") { 
    query=query.OrderBy(h=>h.FrontDoor.Label); 
} 

但是,此功能非常通用,恕我直言。所以,一個實用的功能可以參考SortMemberPath,並在方法中使用它作爲propertyPath,這對於許多其他將使用它的應用程序來說是一個很大的幫助。

我請教這個technique,幫助我在一定程度上使這一實用功能,而只是直接財產訪問是成功的(即:Address),但訪問次屬性(即:FrontDoor.Label)不成功。

請指導我。

+0

請參閱:['使用Linq.Expression'訪問嵌套屬性與動態lambda]](http://stackoverflow.com/questions/1674041/access-nested-properties-with-dynamic-lambda-using-linq-expression ) – user1416420 2013-02-15 07:47:05

+0

或者:[如何在泛型擴展方法中使用字符串列名稱的IQueryable上應用OrderBy?](http://stackoverflow.com/questions/307512/how-do-i-apply-orderby-on- an-iqueryable-using-a-string-column-name-within-a-gene) – Corey 2013-02-15 08:06:30

+0

嗯......'動態查詢'是關鍵字......我會先檢查並測試它。謝謝。 – Roland 2013-02-15 09:27:31

回答