簡體   English   中英

異步編程投影

[英]Projection with asynchronous programming

我正在將異步編程引入我的現有代碼庫,並且在GetStudents()的結果上調用Select()時遇到一些麻煩-收到的錯誤消息如下:“ Task<List<ApplicationUser>>不包含Select的定義”。 我認為這將歸因於語法錯誤,但是任何指導都將不勝感激-謝謝。

   public async Task<List<ApplicationUser>> GetStudents()
    {
        return await Task.Run(() => _context.Users.ToList());
    }


    public async Task<StudentIndexViewModel> CreateStudentRegisterViewModel()
    {
        var model = new StudentIndexViewModel();
        var students = await _studentRepo.GetStudents().
            Select(x => new StudentViewModel
            {
                Forename = x.Forename,
                Surname = x.Surname
            }).ToListAsync();

        model.Students = students;

        return model;
    }

如前所述,該錯誤來自嘗試在Task<T>上調用Select ,這是無效的。 但是,問題遠不止於此。 該代碼當前正在從數據庫獲取整個表,只是從內存結果獲取一些值。 這浪費了數據庫和應用程序服務器中的處理時間。
不僅如此,而且僅使用線程池線程來等待I / O操作是另一種浪費。

總的來說,代碼應該是這樣的。

public async Task<List<ApplicationUser>> GetApplicationUsersAsync()
{
    // use Entity Framework properly with ToListAsync
    // this returns the entire table
    return await _context.Users.ToListAsync();
}

public async Task<List<StudentViewModel>> GetStudentsAsync()
{
    // use Entity Framework properly with ToListAsync
    return await _context.Users
        // this only returns the 2 needed properties
        .Select(x => new StudentViewModel
        {
            Forename = x.Forename,
            Surname = x.Surname
        })
        .ToListAsync();
}


public async Task<StudentIndexViewModel> CreateStudentRegisterViewModel()
{
    var model = new StudentIndexViewModel();
    model.Students = await _studentRepo.GetStudentsAsync();

    return model;
}

_studentRepo.GetStudents()返回Task<List<...>>

錯誤告訴您, Task不是集合,也沒有Select()方法。

您可以使用await來獲取任務內部的集合,但是您需要在await ed值(您的代碼當前為await s Select() )上調用Select() )。

您需要添加括號:

(await ...).Select(...);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM