I have written below ASP.NET API code to return employee data
public async Task<IActionResult> employeegroups()
{
try
{
var employeegroups = _context.EmployeeGroups.Select(p => new EmployeeGroupsEntity()
{
id = p.Key,
name = p.Name
}).ToList();
return Ok(employeegroups);
}
catch
{
return BadRequest();
}
}
I get this warning:
This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread
So, I tried to add `await':
var employeegroups = await _context.EmployeeGroups.Select(p => new EmployeeGroupsEntity()
{
id = p.Key,
name = p.Name
}).ToList();
But I get this warning:
List 'EmployeeGroupsEntity' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type List 'EmployeeGroupsEntity' could be found (are you missing a using directive or an assembly reference?)"
Here is my model:
public class EmployeeGroupsEntity
{
public Guid id { get; set; }
public string name { get; set; }
}
When we are working with Task<T>
as return type of method in combination with async
keyword we should also be using await
keyword that will make sure that the calling thread is not blocked and will resume the method lines execution followed after the await
. So you should be calling the ToListAsync
method with await
like:
var employeegroups = await _context.EmployeeGroups.Select(p => new EmployeeGroupsEntity()
{
id = p.Key,
name = p.Name
}).ToListAsync();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.