【问题标题】:LINQ with JOIN, GROUP, SUM() and return a new SELECTLINQ 与 JOIN、GROUP、SUM() 并返回一个新的 SELECT
【发布时间】:2020-03-10 03:29:35
【问题描述】:

可以执行如下 SQL 的 LINQ:

select invoice.credit, ((sum(detailsInvoice.amount) - sum(detailsInvoice.discount))+ sum(detailsInvoice.tax)) as total
from detailsInvoice
join invoice on detailsInvoice.invoiceID = invoice.ID
where invoice.carga = 1428 and invoice.ID <> 0
group by invoice.credit

我在 SQL 中得到了这个结果

我花了很多时间尝试创建一个 LINQ 来执行该查询,但没有运气。

【问题讨论】:

标签: c# .net entity-framework linq lambda


【解决方案1】:

你应该这样做,请原谅任何拼写错误,没有使用编译器来测试它。

var result = db.invoice.Include(x=>x.detailsInvoice).
                               GroupBy(x=>invoice.credit).
                               Select(y=> new {  
                                credit = y.Key,
                                Total =  (y.Sum(z=>z.detailsInvoice.amount) - y.Sum(z=>z.detailsInvoice.discount) + y.Sum(z=>detailsInvoice.tax))
                                });

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    您的回答让我很好地了解了该怎么做。 我忘了提到的重要一点是 Invoice 表和 detailsInvoice 没有关系。

    这就是我所做的:

    var result = (from _invoice in ruterosContext.Invoice
                    join _details in ruterosContext.DetailsInvoice
                    on new { id = _invoice.ID, reference = _invoice.Reference } equals 
                    new { id = _details.invoiceID, reference = _details.Reference }   
                    where _invoice.ID != 0 && _invoice.Carga == 1428
                    select new {
                        Credit = _invoice.credit,
                        amount = _details.amount,
                        discount = _details.discount, 
                        tax = _details.tax
                    }).GroupBy(x => x.credit).
                         Select(y => new { Credit = y.Key, 
                         Total = (y.Sum(z => z.amount) - y.Sum(z => z.discount)) + y.Sum(x => x.tax) });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      相关资源
      最近更新 更多