dotnet / dotnet/efcore

Group/Join producing wrong totals

Open
#28,483 0 comments 0 reactions 0 assignees View on GitHub
area-query customer-reported
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.

![results1](https://user-images.githubusercontent.com/3191331/179856614-6fbd23ef-94fd-4ff4-bdd3-c3df6db30532.png)

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.

![results2](https://user-images.githubusercontent.com/3191331/179856678-d8d4102e-2b38-436a-b636-edbe2b7fa985.png)

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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.