2010-08-18 62 views
1

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提供OrderByString擴展方法重載使用一()的排序依據和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 

編輯:這是PersonChild表之間的關係:

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行。

顯然,這些都不是我用我真實的項目確切的表名,但你可以看到PersonMother,並與PersonChild之間的關係是如何的不同。

選擇
我已經試過超載Find()接受Selector它選擇p = Personchild = First().Child但返回類型更改爲匿名,而不是通用型。有沒有辦法在OrderBy流程中使用Selector,但仍返回IEnumerable(of TEntity)

+0

人與兒童表之間的關係是什麼? – 2010-08-18 18:05:27

+0

編輯:格式化搞砸了。 每個Person行都有0-n個子行。例如:表Person:PersonId(pk),Table Child:ChildId(pk),PersonId(fk到Person表),姓氏 – 2010-08-18 18:12:44

回答

1

你可以這樣做(C#,對不起......):

people.Select(p => Person = p, Child = p.Children.First()) 
     .OrderBy("Child.LastName") 
     .Select(p => p.Person); 

BTW,沒有"it.你使用System.Linq.Dynamic,並與"it.你使用ESQL。任何一個都行,但你不應該同時使用!

+0

Craig,謝謝你的評論。我手動輸入了代碼片段並意外添加了「it.'。我沒有在真實的代碼中使用它。我已經更新了這個問題,以展示如何使用存儲庫模式,並傳入條件謂詞。我不知道如何在'Find'函數中添加一個選擇器,並且仍然保持通用函數。 – 2010-08-18 18:29:22