C# asp.net核心中的IAsyncEnumerable视图组件返回

C# asp.net核心中的IAsyncEnumerable视图组件返回,c#,asynchronous,asp.net-core-viewcomponent,C#,Asynchronous,Asp.net Core Viewcomponent,我有一个工作正常的项目: 服务类别: public async Task<IAsyncEnumerable<ContratoDTO>> ContratoServiceGetAll() { List<ContratoDTO> listaDeContrato = new List<ContratoDTO>(); listaDeContrato = await ContratoRepository.GetAllA

我有一个工作正常的项目:

服务类别:

 public async Task<IAsyncEnumerable<ContratoDTO>> ContratoServiceGetAll()
    {
        List<ContratoDTO> listaDeContrato = new List<ContratoDTO>();
        listaDeContrato = await ContratoRepository.GetAllAsync().Result.Select(u => new ContratoDTO(u)).ToList();
        return listaDeContrato.ToAsyncEnumerable();
    }
ViewComponent类:

public async Task<IViewComponentResult> InvokeAsync()
    {
        ContratoViewModel listaContrato = new ContratoViewModel
        {
            Contratos = await ContratoSerivce.ContratoServiceGetAll()
        };
         return View(listaContrato);
    }
和共享视图文件夹上的“我的组件”:

   <tbody>
        @if (Model.Contratos != null)
        {
            @foreach (var item in Model.Contratos.ToEnumerable())
            {

                <tr>
                    <th scope="row">@item.NuContrato</th>
                    <td>@item.VlContrato</td>
                    <td>36</td>
                    <td>@item.DtEmissao</td>
                    <td>@item.DtRetorno</td>
                    <td>Rio de Janeiro</td>
                </tr>
            }
        }
    </tbody>
它是有效的,但是Model.Contratos.ToEnumerable是最好的方法吗?如果我取出ToEnumerable方法,它将抛出一个错误:

'Error CS0202: foreach requires that the return type 'IAsyncEnumerator<ContratoDTO>' of 'IAsyncEnumerable<ContratoDTO>.GetEnumerator()' must have a suitable public MoveNext method and public'

ps:ContratoViewModel有一个IAsyncenenumerable泛型类型T my DTO的属性。

在我使用堆栈溢出的所有年份中,这是我第一次响应任何人,因为我认为是时候为社区做出贡献了。我希望这是有帮助的

可以在类似的任务上等待IAsyncEnumerable。它不需要包装。对问题的注释表明,如果使用.Result.Selectu=>new contractoduu.ToList;,您可能会失去IAsyncEnumerable的优势;。我同意。ToList是同步的,会一直阻塞直到它完成

在使用服务类中的变量时,以下是一个简短的修订:

public async IAsyncEnumerable<ContratoDTO> ContratoServiceGetAll()
{
    foreach (var u in await ContratoRepository.GetAllAsync())
        yield return new ContratoDTO(u);
}
此外,组件中的.ToEnumerable语句假设您的意思是.AsEnumerable from extension method Enumerable.AsEnumerable此IEnumerable源将导致视图在此时阻塞以执行Model.Contractos查询,假设ContractoRepository.GetAllAsync返回IQueryable

有.ToEnumerable是多余的,因为迭代将在Model.Contractos中的@foreach var项开始一次。

.Result.Selectu=>new ContratToToToU.ToList;似乎失去了使用iSyncEnumerable的好处。