如何在EF Core 3.1中以异步方式使用GroupBy? [英] How to use GroupBy in an asynchronous manner in EF Core 3.1?

查看:659
本文介绍了如何在EF Core 3.1中以异步方式使用GroupBy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将GroupBy用作对EFCore的LINQ查询时,出现错误 System.InvalidOperationException:不支持客户端GroupBy

When I use GroupBy as part of a LINQ query to EFCore, I get the error System.InvalidOperationException: Client-side GroupBy is not supported.

这是因为EF Core 3.1尝试尽可能在服务器端评估查询,而不是在客户端评估,并且调用无法

This is because EF Core 3.1 attempts to evaluate queries on the server-side as much as possible, as opposed to evaluating them on the client-side, and the call cannot be translated to SQL.

因此以下语句不起作用,并产生上述错误:

So the following statement does not work, and produces the error mentioned above:

var blogs = await context.Blogs
    .Where(blog => blog.Url.Contains("dotnet"))
    .GroupBy(t => t.BlobNumber)
    .Select(b => b)
    .ToListAsync();

现在显然解决方案是在调用GroupBy之前使用.AsEnumerable()或.ToList() (),因为它明确告诉EF Core您要对客户端进行分组。在GitHub上对此> 在Microsoft文档中

Now apparently the solution is to use.AsEnumerable() or .ToList() before the call to GroupBy(), as that explicitly tells EF Core that you want to do the grouping client side. There is a discussion about this on GitHub and in the Microsoft docs.

var blogs = context.Blogs
    .Where(blog => blog.Url.Contains("dotnet"))
    .AsEnumerable()
    .GroupBy(t => t.BlobNumber)
    .Select(b => b)
    .ToList();

但是,这不是异步的。如何使它异步?

However, this is not asynchronous. How can I make it asynchronous?

如果我将AsEnumerable()更改为AsAsyncEnumerable(),则会收到错误消息。如果我改为尝试将AsEnumerable()更改为ToListAsync(),则GroupBy()命令将失败。

If I change AsEnumerable() to AsAsyncEnumerable(), I get an error. If I instead try to change AsEnumerable() to ToListAsync() then the GroupBy() command fails.

我正在考虑将其包装在Task.FromResult中,但这实际上是异步的吗?还是数据库查询仍然是同步的,只有随后的分组是异步的?

I am thinking of wrapping it in a Task.FromResult, but would this actually be asynchronous? Or is the database query still synchronous and only the subsequent grouping is asynchronous?

var blogs = await Task.FromResult(context.Blogs
    .Where(blog => blog.Url.Contains("dotnet"))
    .AsEnumerable()
    .GroupBy(t => t.BlobNumber)
    .Select(b => b)
    .ToList());

如果这不起作用,还有另一种方法吗?

Or if that doesn't work is there another way?

推荐答案

我认为您唯一的办法就是这样做

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();

因为GroupBy仍将在客户端进行评估

Because GroupBy will be evaluated at client anyway

这篇关于如何在EF Core 3.1中以异步方式使用GroupBy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆