InvalidOperationException: The LINQ expression 'GroupByShaperExpression:

Viewed 4133
fileMovementRepository.GetAll()
                    .Where(fm => repository.GetAll().Select(f => f.Id).Contains(fm.FileId) && fm.TransferredById == userId)
                    .Include(f => f.User).Include(f => f.File).ThenInclude(f => f.Category)
                    .OrderByDescending(f => f.MovedOn)
                    .GroupBy(f => f.FileId)
                    .Select(f=>f.First())
                    .ToList();

The following error is showing on runtime

An unhandled exception occurred while processing the request. InvalidOperationException: The LINQ expression 'GroupByShaperExpression: KeySelector: f.FileId, ElementSelector:EntityShaperExpression: EntityType: FileMovement ValueBufferExpression: ProjectionBindingExpression: EmptyProjectionMember IsNullable: False

.First()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information. Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)

InvalidOperationException: The LINQ expression 'GroupByShaperExpression: KeySelector: f.FileId, ElementSelector:EntityShaperExpression: EntityType: FileMovement ValueBufferExpression: ProjectionBindingExpression: EmptyProjectionMember IsNullable: False .First()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

1 Answers

Use ToList() before GroupBy and it will work as expected.

fileMovementRepository.GetAll()
                .Where(fm => repository.GetAll().Select(f => f.Id).Contains(fm.FileId) && fm.TransferredById == userId)
                .Include(f => f.User).Include(f => f.File).ThenInclude(f => f.Category)
                .OrderByDescending(f => f.MovedOn)
                .ToList()
                .GroupBy(f => f.FileId)
                .Select(f=>f.First())
                .ToList();
Related