簡體   English   中英

如何按子實體的屬性分組並獲取 linq 中子實體的總和?

[英]How to group by property of child entity and get sum of child entity in linq?

我需要按子實體對數據進行分組並獲得子實體的總和。 所以,我嘗試了這個 linq:

context.Parent.Include(p => p.Child).GroupBy(p => p.Child.Type).Select(g => g.Sum(p => p.Child.Amount));

以上 linq 導致錯誤。 但是,如果我要獲得父實體的總和,它將起作用。

context.Parent.Include(p => p.Child).GroupBy(p => p.Child.Type).Select(g => g.Sum(p => p.Amount));

為什么我不能得到子實體的總和?

這是限制。 在 GroupBy 之后,您不能使用導航屬性。 同樣在 GroupBy 之后,所有的 Includes 都被完全忽略,所以省略它們。

您的查詢可以寫成以下方式:

var query = 
    from p in context.Parent
    group p.Child by p.Child.Type into g
    select new 
    {
        Type = g.Key,
        Sum = g.Sum(c => c.Amount)
    };

Lambda 語法變體:


var query = context.Parent
    .GroupBy(p => p.Child.Type, p => p.Child)
    .Select(g => new 
    {
       Type = g.Key, 
       Sum = g.Sum(c => c.Amount)
    });

顯然,在您的Parents中,您有一系列 parents 。 每個Parent都有一個屬性Child 每個Child都有兩個屬性: AmountType

您忘記告訴我們您的規范,並給了我們一些不符合您要求的代碼。 所以我們很難知道你想要什么。

我認為您希望創建具有相同值的Parent.Child.Type Parents 從組中的每個 Parent 中獲取Parent.Child.Amount的值並對這些值求和。

你是對的,為此你應該使用 Enumerable.GroupBy 的重載之一。 我的建議是使用具有參數 resultSelector 的重載:

// make groups of Parents with same value of Parents.Child.Type:
var result = dbContext.Parents.GroupBy(parent => parent.Child.Type,

// parameter resultSelector: for every Type, and all Parents that have this Child.Type
// make one new:
(type, parentsWithThisChildType) => new
{
    // do you want to know the type?
    ChildType = type,

    // from all parents in this group, select the Parent.Child.Amount and Sum them:
    TotalChildAmounts = parentsWithThisChildType
        .Select(parent => parent.Child.Amount)
        .Sum(),
})

換句話說:從您的父母序列中,創建具有相同 Parent.Child.Type 值的父母組。 從每組中制作一個 object,如下所示:

  • 可取,取本組所有Parent.Child.Type的通用Type
  • 來自組中的每個 Parent,select Parent.Child.Amount 的值。
  • 將這個 Amound 的所有值相加,並將結果放入 TotalChildAmounts

暫無
暫無

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

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