Note: I realize this question is similar to another question , however that question was asked in the context of Genom-e and remains unanswered. My question is in the context of LINQ DynamicQuery.在一到許多相關的表
我使用System.Linq.Dynamic
提供OrderBy
的String
擴展方法重載使用一()的排序依據和DynamicQuery。將字符串傳遞給OrderBy
效果很好。我可以對主要實體字段進行排序,例如:person.OrderBy("LastName")
,只要父代與子代之間存在一對一關係,即:person.OrderBy("Mother.LastName")
,我可以對子實體字段進行排序。
但是,如果與父母和孩子存在一對多關係,例如:person.OrderBy("Children.LastName")
,我無法對孩子的字段進行排序。這會引發一個錯誤:No property or field 'Children' exists in type 'Person'
。
很明顯這會失敗,因爲解釋器不知道哪個孩子的LastName
我試圖在排序操作中使用。我可以通過創建一個像這樣的表達式來輕鬆解決這個問題(Function(p As Person) p.Children.First.LastName)
。
但是,如何在使用OrderBy
的字符串文字擴展名時獲得類似的First
行爲?最後,我希望能夠做這樣的事情:person.OrderBy("it.Lastname desc, Children.First().FirstName asc")
編輯:我使用Repository模式,這就是我的Find
函數看起來像:
Public Function Find(ByVal predicate As Expression(Of Func(Of TEntity, Boolean)), ByVal orderBy As String, ByVal skip As Integer, ByVal take As Integer) As IEnumerable(Of TEntity) Implements ILinqSqlRepository(Of TEntity, TContext).Find
If String.IsNullOrEmpty(orderBy) Then
Return Find(predicate, skip, take)
Else
Dim qry = Context.GetTable(Of TEntity)().Where(predicate).OrderBy(orderBy).Skip(skip).Take(take)
Return qry.ToList()
End If
End Function
編輯:這是Person
和Child
表之間的關係:
Person Table
PersonId (pk)
MotherId (fk to Mother Table)
LastName
FirstName
Child Table
ChildId (pk)
PersonId (fk to Person Table)
LastName
FirstName
Mother Table
MotherId (pk)
LastName
FirstName
每個Person
可能有0個或更多Children
。您可以看到每個Person
可以有0或1個Mother
行。
顯然,這些都不是我用我真實的項目確切的表名,但你可以看到Person
和Mother
,並與Person
和Child
之間的關係是如何的不同。
選擇
我已經試過超載Find()
接受Selector
它選擇p = Person
和child = First().Child
但返回類型更改爲匿名,而不是通用型。有沒有辦法在OrderBy
流程中使用Selector
,但仍返回IEnumerable(of TEntity)
?
人與兒童表之間的關係是什麼? – 2010-08-18 18:05:27
編輯:格式化搞砸了。 每個Person行都有0-n個子行。例如:表Person:PersonId(pk),Table Child:ChildId(pk),PersonId(fk到Person表),姓氏 – 2010-08-18 18:12:44