我正在使用ef core 2.2和LINQ。我正在尝试在同一查询中聚合多个列。 LINQ生成的sql查询不正确,并产生不正确的结果。
public async Task<SecondaryInvoiceLProformaTotals> test(int secondaryInvoiceId)
{
var query = (_context.SecondaryInvoiceLineItems
.Where(i => i.SecondaryInvoiceId == secondaryInvoiceId)
.GroupBy(l => new {l.SecondaryInvoiceId})
.Select(g => new SecondaryInvoiceLProformaTotals
{
SecondaryInvoiceId = g.Key.SecondaryInvoiceId,
SumInvoiceQty = g.Sum(o => o.InvoiceQty),
SumMRPAmount = g.Sum(o => o.TotalMRPAmount),
SumSecondaryDiscountAmount = g.Sum(o => o.TotalSecondaryDiscountAmount),
SumSecondaryPrice = g.Sum(o => o.TotalSecondaryPrice),
SumIGSTAmount = g.Sum(o => o.TotalIGSTAmount),
SumCGSTAmount = g.Sum(o => o.TotalCGSTAmount),
SumSGSTAmount = g.Sum(o => o.TotalSGSTAmount),
SumAmount = g.Sum(o => o.TotalAmount),
SumBasePoints = g.Sum(o => o.TotalBasePoints)
})
);
SecondaryInvoiceLProformaTotals ret = await query.FirstOrDefaultAsync();
return ret;
}
LINQ生成的SQL查询:
SELECT SUM("i"."InvoiceQty") AS "SumInvoiceQty",
"i"."TotalMRPAmount" AS "SumMRPAmount",
"i"."TotalSecondaryDiscountAmount" AS "SumSecondaryDiscountAmount",
"i"."TotalSecondaryPrice" AS "SumSecondaryPrice",
"i"."TotalIGSTAmount" AS "SumIGSTAmount",
"i"."TotalCGSTAmount" AS "SumCGSTAmount",
"i"."TotalSGSTAmount" AS "SumSGSTAmount",
"i"."TotalAmount" AS "SumAmount",
SUM("i"."TotalBasePoints") AS "SumBasePoints"
FROM "SecondaryInvoiceLineItems" AS "i"
WHERE "i"."SecondaryInvoiceId" = 5
GROUP BY "i"."SecondaryInvoiceId"
LIMIT 1
预期的SQL查询:
SELECT SUM("i"."InvoiceQty") AS "SumInvoiceQty",
SUM("i"."TotalMRPAmount") AS "SumMRPAmount", SUM("i"."TotalSecondaryDiscountAmount") AS "SumSecondaryDiscountAmount",
SUM("i"."TotalSecondaryPrice") AS "SumSecondaryPrice",
SUM("i"."TotalIGSTAmount") AS "SumIGSTAmount",
SUM("i"."TotalCGSTAmount") AS "SumCGSTAmount",
SUM("i"."TotalSGSTAmount") AS "SumSGSTAmount",
SUM("i"."TotalAmount") AS "SumAmount",
SUM("i"."TotalBasePoints") AS "SumBasePoints"
FROM "SecondaryInvoiceLineItems" AS "i"
WHERE "i"."SecondaryInvoiceId" = 5
GROUP BY "i"."SecondaryInvoiceId"
LIMIT 1