Client Side Groupby Is Not Supported

Client side GroupBy is not supported

Your .GroupBy(y => y.LanguageCode).ToDictionaryAsync(y => y.Key, y => y.Select(z => z.Name)); cannot be converted to SQL.
EF Core 3.0 will throw exception to make sure you know that all records in Units will be fetched from database before grouping and map to Dictionary.

It's top breaking change in EF Core 3.0.
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes

EFCore 3 GroupBy+ToDictionary raises client side GroupBy is not supported

After any group by, there should be a Select statement which uses only the Group Key (and it's properties) and aggregates. This is similar to the limitation in Sql languages. As an optimization, the EF core team could possibly support calling ToDictionary with the same limitation, but they've not, so we need to do it manually:

IEnumerable<int> ids = new List<int> { 1, 2, 3 };
var q = db.Comments.Where(x => ids.Contains(x.Identifier))
.GroupBy(x => x.Identifier)
.Select(x => new { x.Key, Count = x.Count()});
var map = await q.ToDictionaryAsync(x => x.Key, x => x.Count);

This will be translated successfully.

Unable to translate the given 'GroupBy' pattern. Call 'AsEnumerable' before 'GroupBy' to evaluate it client-side

Since you load all records, you have to group on the client-side. Note that after materialising objects, you cannot use Async queryable extensions.

public async Task<Dictionary<string, List<string>>> GetAllListsAsync() =>
(await _context.ListItems.ToListAsync())
.GroupBy(x => x.Code)
.OrderBy(x => x.Key)
.ToDictionary(x => x.Key, x => x.Select(y => y.Value)
.OrderBy(v => v)
.ToList());

How to use GroupBy in an asynchronous manner in EF Core 3.1?

I think the only way you have is just to do it something like this

var blogs = await context.Blogs
.Where(blog => blog.Url.Contains("dotnet"))
.ToListAsync();

var groupedBlogs = blogs.GroupBy(t => t.BlobNumber).Select(b => b).ToList();

Because GroupBy will be evaluated at client anyway



Related Topics



Leave a reply



Submit