dotnet / dotnet/efcore

Translate custom aggregate functions without GroupBy

Open
#29,200 13 comments 16 reactions 0 assignees View on GitHub
area-query needs-design
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

Max can be used over a collection navigation in a projection:

```c#
_ = await ctx.Authors
.Select(a => new { Author = a, Books = a.Books.Max(b => b.Id) })
.ToArrayAsync();
```

```sql
SELECT [a].[Id], [a].[Name], (
SELECT MAX([b].[Id])
FROM [Books] AS [b]
WHERE [a].[Id] = [b].[AuthorId]) AS [Books]
FROM [Authors] AS [a]
```

However, the same can't be done with string.Join:

```c#
_ = await ctx.Authors
.Select(a => new { Author = a, Books = string.Join(", ", a.Books.Select(b => b.Name)) })
.ToArrayAsync();
```

(this causes client evaluation)

The query above can be rewritten using a GroupBy, which does work:

```c#
_ = await ctx.Books
.GroupBy(b => b.Author)
.Select(g => new { Author = g.Key, Books = string.Join(", ", g.Select(b => b.Name)) })
.ToArrayAsync();
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.