Group/Join producing wrong totals
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
I have the following query.
var query = from r in DbContext.Railcars
where r.Facility.Company.CompanyCode == companyCode && r.Departure == null
group r by r.Product into productGroup
select new
{
Product = productGroup.Key,
Original = productGroup.Sum(r => (long)r.Volume),
Offloaded = productGroup.SelectMany(r => r.TruckRailcars).Sum(tr => (long)tr.Volume)
};
var x = query.ToList();
Here's the generated SQL.
``` sql
DECLARE @__companyCode_0 nvarchar(80) = N'USRAILOGL';
SELECT [r].[Product], COALESCE(SUM(CAST([r].[Volume] AS bigint)), CAST(0 AS bigint)) AS [Original], COALESCE(SUM(CAST([t].[Volume] AS bigint)), CAST(0 AS bigint)) AS [Offloaded]
FROM [Railcars] AS [r]
INNER JOIN [Facilities] AS [f] ON [r].[FacilityId] = [f].[Id]
INNER JOIN [Companies] AS [c] ON [f].[CompanyId] = [c].[Id]
INNER JOIN [TruckRailcars] AS [t] ON [r].[Id] = [t].[RailcarId]
WHERE ([c].[CompanyCode] = @__companyCode_0) AND ([r].[Departure] IS NULL)
GROUP BY [r].[Product]
```
And here are the results.

These numbers are wrong. The `Original` values are too large.
If I comment out the assignment to `Offloaded` in the `select` clause, then I get the following SQL.
```sql
DECLARE @__companyCode_0 nvarchar(80) = N'USRAILOGL';
SELECT [r].[Product], COALESCE(SUM(CAST([r].[Volume] AS bigint)), CAST(0 AS bigint)) AS [Original]
FROM [Railcars] AS [r]
INNER JOIN [Facilities] AS [f] ON [r].[FacilityId] = [f].[Id]
INNER JOIN [Companies] AS [c] ON [f].[CompanyId] = [c].[Id]
WHERE ([c].[CompanyCode] = @__companyCode_0) AND ([r].[Departure] IS NULL)
GROUP BY [r].[Product]
```
And now I get these results.

These numbers are correct!
Apparently, the additional join to `TruckRailcars` is causing additional rows to increase my totals. But given my original LINQ query, does this seem right?
EF Core version:
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0
Operating system: Windows 11
IDE: Visual Studio 2022
Contributor guide
Assessment
This issue has not been assessed yet.