在 C# 中需要帮助分组

Need Help Grouping in C#

我有以下代码可以按发票编号对付款金额进行分组

我尝试使用以下代码按 InvoiceNumber 分组,如下所示,但出现 InvalidOperationException: The LINQ expression GroupByShaperExpression' 异常。

我要完成

 Type       Amount    InvoiceNumber
 1                 0       123
 2                         123
 3                 0       123
 4                 00      123
 1                 0       124
 1                 0       124
 3                 0       124
 3                 0       124
 4                 0       124

我想按发票编号分组并对类型 = 1&2 的金额字段的值求和,显示为利息,3&4 显示为 Princepal

InvoiceNumber       Interest   Princepal
123                 0        00
124                 0        0

有几个问题:

  • EF Core 在 GroupBy
  • 之后无法访问导航属性
  • 即使 EF Core 可以翻译这个查询,它也是无效的。

考虑按以下方式重写查询:

var ProductPaymentIDs = ProductPayments.Select(pp => pp.ID).ToList();

var query =
    from cl in Context.PaymentCodingLines
    where ProductPaymentIDs.Contains(cl.ProductPaymentID)
    group new { cl.InvoiceLineNav.TypeID, cl.Amount } by g.InvoiceLineNav.InvoiceNav.InvoiceNumber into g
    select new DetailDTO
    {
        InvoiceNumber = g.Key,
        InterestPaid = g.Sum(x => x.TypeID == 1 || x.TypeID == 2 ? x.Amount : 0),
        PrincipalPaid = g.Sum(x => x.TypeID == 3 || x.TypeID == 4 ? x.Amount : 0)
    };

var Details = query.ToList();