如何在存储库类中使用 IAsyncEnumerable

Sha*_*ngh 11 c# asp.net-core-webapi c#-8.0 asp.net-core-3.1 ef-core-3.1

我正在使用 .net core 3.1 和 EF core 创建一个小型 API。
我尝试在我的存储库类中使用 IAsyncEnumerable 但出现错误。
我知道错误是有效的,但有人可以告诉我如何在存储库类中使用 IAsyncEnumerable 吗?

状态库.cs

    public class StateRepository : IStateRepository
    {
        public StateRepository(AssetDbContext dbContext)
            : base(dbContext)
        {

        }

        public async Task<State> GetStateByIdAsync(Guid id)
            => await _dbContext.States
                .Include(s => s.Country)
                .FirstOrDefaultAsync(s => s.StateId == id);

        public async IAsyncEnumerable<State> GetStates()
        {
            // Error says:
            //cannot return a value from iterator. 
            //Use the yield return statement to return a value, or yield break to end the iteration
             return await _dbContext.States
                       .Include(s => s.Country)
                       .ToListAsync();
        }
    }
Run Code Online (Sandbox Code Playgroud)

谁能告诉我哪里出错了?
谢谢

Min*_*ata 14

IAsyncEnumerable 并不是你想象的那样。

IAsyncEnumerable 在使用“yield”关键字的异步方法中使用。IAsyncEnumerbale 允许它一项一项地返回每一项。例如,如果您正在从事物联网方面的工作,并且您希望在结果出现时对其进行“流式传输”。

static async IAsyncEnumerable<int> FetchIOTData()
{
    for (int i = 1; i <= 10; i++)
    {
        await Task.Delay(1000);//Simulate waiting for data to come through. 
        yield return i;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您对 IAsyncEnumerable 更多感兴趣,您可以在这里阅读更多内容: https: //dotnetcoretutorials.com/2019/01/09/iasyncenumerable-in-c-8/

就您而言,您没有使用 Yield,因为您从一开始就拥有整个列表。您只需要使用常规的旧任务即可。例如 :

public async Task<IEnumerable<<State>> GetStates()
{
    // Error says:
    //cannot return a value from iterator. 
    //Use the yield return statement to return a value, or yield break to end the iteration
     return await _dbContext.States
               .Include(s => s.Country)
               .ToListAsync();
}
Run Code Online (Sandbox Code Playgroud)

如果您正在调用某个一一返回状态的服务,并且您想一一读取这些状态,那么您将使用 IAsyncEnumerable。但是根据您给出的示例(坦率地说,大多数用例),您只需使用 Task 就可以了

  • 他可以使用返回类型 asAsyncEnumerable 并将 db 作为流读取 (2认同)