Skip to content

Widely-used DistinctBy workaround causes other errors #34119

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
lonix1 opened this issue Jun 29, 2024 · 2 comments
Closed

Widely-used DistinctBy workaround causes other errors #34119

lonix1 opened this issue Jun 29, 2024 · 2 comments

Comments

@lonix1
Copy link

lonix1 commented Jun 29, 2024

Originally asked on SO without resolution.


A query:

List<Guid> productCodes = GetProductCodes();  
var products = await _context
  .Products
  .Where(x => productCodes.Contains(x.ProductCode))
  .GroupBy(x => x.ProductCode).Select(x => x.First())    // workaround for `DistinctBy`
  .Select(x => new { SupplierId = x.Supplier.Id, WarehouseId = x.Warehouse.Id, x.ProductCode, x.Price, ... })
  .ToListAsync();

Result:

InvalidOperationException: The LINQ expression 'ProjectionBindingExpression: 0' 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'.

I use the GroupBy/Select-First workaround instead of DistinctBy which is currently unsupported.

I assume from the error message that the projection in .Select() is the problem; when I remove that the query works. I could perform the projection afterwards, but then I'd be fetching large quantities of data for nothing.

Is there a way to workaround this issue until there is DistinctBy support?

EF Core version: 7.0.16
Database provider: Npsql
Target framework: 7.0
Operating system: linux
IDE: vscode 1.90.2

@roji
Copy link
Member

roji commented Jun 29, 2024

7.0 is out of support, please upgrade to 8.0 and confirm that the issue is still present there.

@lonix1
Copy link
Author

lonix1 commented Jun 29, 2024

I'll do that and reopen if necessary, thank you.

@lonix1 lonix1 closed this as completed Jun 29, 2024
@roji roji closed this as not planned Won't fix, can't repro, duplicate, stale Jun 29, 2024
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

2 participants