【问题标题】:How to use IAsyncEnumerable in repository class如何在存储库类中使用 IAsyncEnumerable
【发布时间】:2020-10-25 02:57:55
【问题描述】:

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

StateRepository.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();
        }
    }

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

【问题讨论】:

    标签: c# asp.net-core-webapi asp.net-core-3.1 ef-core-3.1 c#-8.0


    【解决方案1】:

    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;
        }
    }
    

    如果您对 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();
    }
    

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

    就可以了

    【讨论】:

    • 他可以使用返回类型 asAsyncEnumerable 并将 db 作为流读取
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多