efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Doing a Sum() or Count() in the same query results in incorrect data

Open olliholliday opened this issue 10 years ago • 4 comments

I'm having a problem with ef7 rc1 where the queries don't result in errors but return incorrect data:

            return dbContext.Set<Playlist>()
                .OrderBy(x => x.Name)
                .Select(x => new PlaylistViewModel {
                    Name = x.Name,
// get the total duration attached entities via configured navigation property
                    TotalDuration = x.Entries.Sum(y => y.Duration),
// get the number of attached entities via configured navigation property
                    Entries = x.Entries.Count
                });

This results in data where both TotalDuration and Entries are set to the same value - somewhere in the entity projection it set both TotalDuration and Entries to the SUM() result - which is incorrect.

The SQL it generated is below:

SELECT (
    SELECT SUM([y].[Duration])
    FROM [Playlist].[PlaylistEntry] AS [y]
    WHERE [x].[PlaylistId] = [y].[PlaylistId]
), [x].[Name]
FROM [Playlist].[Playlist] AS [x]
ORDER BY [x].[Name]

I found that if I change the order of the sum/count in the LINQ that I would get both TotalDuration and Entries set to the COUNT() result instead - again incorrect but without any error messages.

When I tried to introduce a join it resulted in returning all of the data from the database and calculating the Sum() and Count() in memory - producing the correct results. This is the solution I've stuck with for the time being though I'd appreciate any help in improving it.

I've pasted the domain model, dbcontext and the other experiments where I tried to get the results I needed here: http://pastebin.com/75rVrhLZ

Thanks a lot

olliholliday avatar Mar 16 '16 23:03 olliholliday

In what I suspect is another manifestation of the same problem, I've found that if you use Count twice for the same entity set in the same query but with different criteria, the resulting query just has a single COUNT clause, the result of which gets used for both, when it should be creating two different COUNT clauses. (I'm using the SQL Server provider, in RC1.)

For example, something of this form:

dbContext
  .BundleVmSets
  .Select(s => new
  {
      Running = s.BundleVms.Count(vm => vm.IsRunning),
      Provisioned = s.BundleVms.Count(vm => vm.IsProvisioned)
  });

will only count for one out of the two specified criteria, and then use that one calculated count for both results.

idg10 avatar Mar 29 '16 07:03 idg10

dupe of #3616 ?

smitpatel avatar Mar 29 '16 13:03 smitpatel

Most likely, but will double check to make sure

maumar avatar Mar 29 '16 16:03 maumar

Verified that it is a duplicate of https://github.com/aspnet/EntityFramework/issues/3616 and that it is fixed in the current bits, closing

maumar avatar Mar 30 '16 01:03 maumar