viraptor
viraptor

Reputation: 34205

Entity Framework GroupBy throwing InvalidOperationException

I'm trying to GroupBy my results based on a joined table.

var services = await db.Services.AsNoTracking()
    .Include("Visit")
    .Where(s => !s.Cancelled && s.AmtToPay > 0 && patientIds.Contains(s.Visit.PatientNo) && s.DTS < day)
    .GroupBy(s => s.Visit.PatientNo)
    .ToListAsync(cancellationToken);

Unfortunately this GroupBy causes an exception:

System.InvalidOperationException : The client projection contains a reference to a constant expression of 'Microsoft.EntityFrameworkCore.Metadata.IPropertyBase' which is being passed as an argument to the method 'ValueBufferTryReadValue'. This could potentially cause a memory leak; consider assigning this constant to a local variable and using the variable in the query instead. See https://go.microsoft.com/fwlink/?linkid=2103067 for more information.

Which doesn't really explain the situation. How do I use GroupBy in this situation?

Upvotes: 0

Views: 531

Answers (1)

Okan Karadag
Okan Karadag

Reputation: 3055

select should be added after groupby in EntityFramework Core

var services = await db.Services.AsNoTracking()
    .Include("Visit")
    .Where(s => !s.Cancelled && s.AmtToPay > 0 && patientIds.Contains(s.Visit.PatientNo) && s.DTS < day)
    .GroupBy(s => s.Visit.PatientNo)
    .Select(s => s.Key)
    .ToListAsync(cancellationToken);

according to ef core 3.1 breaking changes notes

Starting with 3.0, EF Core only allows expressions in the top-level projection (the last Select() call in the query) to be evaluated on the client. When expressions in any other part of the query can't be converted to either SQL or a parameter, an exception is thrown.

Upvotes: 1

Related Questions