在 ASP.NET Core 6 中,控制器操作返回的 IQueryable 对象默认是同步枚举的。如果需要异步枚举,请使用 AsAsyncEnumerable() 方法,该方法在 System.Linq.Async 命名空间中定义。
示例代码:
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore;
[ApiController] [Route("[controller]")] public class ValuesController : ControllerBase { private readonly ApplicationDbContext _context;
public ValuesController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async Task GetAsync()
{
IQueryable values = _context.Values;
return Ok(await values.AsAsyncEnumerable().ToListAsync());
}
}