Maybe it's by design, but I have this strange example:
var attendees = await _dbContext.Attendees
.Include(x => x.CourseAttends.Where(y => y.Status == "attended"))
.ToListAsync();
I know that the first attendee in the query has 2 CourseAttends
. The first with status attended
and the second with cancelled
.
If I do a foreach
, the query returns a single CourseAttend
for the Attendee
. That's good.
Now, if I want a list of attendees, that have only 1 attended
CourseAttend
, I change the query to:
var attendees = await _dbContext.Attendees
.Include(x => x.CourseAttends.Where(y => y.Status == "attended"))
.Where(x => x.CourseAttends.Count == 1)
.ToListAsync();
This time the first attendee is NOT included in the query, because it counts 2 (the 'cancelled' is included).
Is that how it should work?
I'm aware that I could build the query different, like:
var attendees = await _dbContext.Attendees.Where(x => x.CourseAttends.Count(y => y.Status == "attended") == 1))
.ToListAsync();
...but my real query is far more complex.
THE SQL FROM EF:
SELECT [a].[Id], [a].[Email], [a].[FirstName], [a].[LastName], [t].[Id], [t].[AttendeeId], [t].[Status] FROM [Attendees] AS [a] LEFT JOIN ( SELECT [c].[Id], [c].[AttendeeId], [c].[Status] FROM [CourseAttendees] AS [c] WHERE [c].[Status] = N'attended' ) AS [t] ON [a].[Id] = [t].[AttendeeId] WHERE ( SELECT COUNT(*) FROM [CourseAttendees] AS [c0] WHERE [a].[Id] = [c0].[AttendeeId]) = 1
It looks like EF counts ALL the attendees CourseAttends and not just the ones with status 'attended'?