簡體   English   中英

使用 LINQ-to-Entities 選擇父對象時對子對象進行排序

[英]Sort child objects while selecting the parent using LINQ-to-Entities

想象一下,您有一些 Entity Framework 實體看起來像這樣(顯然不是這些特定的類,而是帶有所有實體框架管道的自動生成的類;這些只是為了說明):

public class Parent
{
    public int ID { get; set; }
    public List<Child> Children { get; set; }
}

public class Child
{
    public int ID { get; set; }
    public Parent Parent { get; set; }
    public int Number { get; set; }
}

我有一個如下所示的 LINQ 查詢:

from parent in context.Parents.Include("Child")
select parent

但是,這將返回子項按 ID 順序排列的父項列表。 我希望孩子們在他們的父級中按他們的 Number 屬性排序。 如何才能做到這一點?

編輯:澄清:這個想法是將查詢隱藏在方法調用(在層外觀中)后面,該方法調用只返回IList<Parent> 這使得使用匿名類查詢和手動排序等解決方案很痛苦(與某些萬能解決方案相比,您可以在查詢或其他方面進行操作)。

Alex James 在這個技巧中討論了這個問題。

本質上,根據標准關系建模,關系被認為是無序的。 所以你不能對它們進行排序。 但是您可以投影到其他可以排序的集合上。

看看這個帖子 你可以嘗試這樣的事情:

var query = ((from parent in context.Parents
              from child in parent.Child
              orderby child.Number ascending
              select parent) as ObjectQuery<Parent>
            ).Include("Child");

一種選擇是在內存中執行查詢和排序(例如在輸出上)。

var parents = context.Parents.Include("Child").ToList(); //note that ToList is here just to execute the query and get the objects in memory

foreach (var p in parents)
{
   //do something with parent item
   foreach (var c in p.Child.OrderBy(c => c.Number))
   {
      /do something with the child item
   }
}

還有另外兩個選項似乎也各有優缺點:

子查詢中的LINQ“.Include”orderby

LINQ OrderBy Name ThenBy ChildrenCollection.Name

這是我做過的事情:

var query = from parent in context.Parents 
            select new 
            {
                 parent,
                 childs = from child in context.Child
                            orderby child.ID ascending
                            select new
                            {
                                 child
                            }
            }

我實現了這樣的東西,它對我來說效果很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM