c# - Projection with asynchronous programming
问题描述
I'm introducing asynchronous programming to my existing code base and having some trouble with calling Select() on the result of GetStudents() - the error message received is as follows "Task<List<ApplicationUser>>
does not contain a defintion for Select". I think it'll be due to incorrect syntax, but any guidance would be appreciated - thanks.
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
a Task<T>
,这是无效的。然而,问题远不止于此。该代码目前正在从数据库中获取整个表,只是为了从结果in-memory中获取一些值。这在数据库和应用程序服务器中都浪费了处理时间。
不仅如此,使用线程池线程只是为了等待 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;
}
推荐阅读
- python-3.x - 如何在嵌套的 sklearn 对象中优化 n_jobs 的使用?
- c# - 为什么“未分配的本地可变量”错误出现在一个函数中,但没有出现在第二个非常相似的函数中
- c# - 在从 c# 运行的脚本中使用自定义 python 模块
- c++ - 从对话框写入 main.cpp 中定义的全局数组时,在释放模式下崩溃
- php - PHP禁用特定标头的缓存?
- javascript - 试图在 Jest 中模拟一个命名的 commonjs 模块
- javascript - 具有 2 级嵌套的多线图,从 v4 到 v5 的转换问题
- mysql - 来自两个组合查询的数据显示不正确
- amazon-web-services - 我是否需要为未通过基本请求验证的 Amazon API Gateway 请求付费?
- botframework - 如果他/她发现输入的输入不正确,我如何提示用户重新输入上一个瀑布步骤的输入