我将异步编程引入到我现有的代码库中,并且在对 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;
}
至于有人提到,错误来自于试图调用Select
上Task<T>
,这是无效的。然而,问题远不止于此。该代码目前正在从数据库中获取整个表,只是为了从内存中的结果中获取一些值。这在数据库和应用程序服务器中都是一种处理时间的浪费。
不仅如此,使用线程池线程只是为了等待 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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句