Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous Web API Endpoint

The following Web API end point is still getting the following error:

"A second operation started on this context before a previous asynchronous operation completed."

Since I'm using the .ToListAsync with the data returned from Entity Framework, I'm assuming the problem is with the var user line blocking.

How do I make that part async as well?

[Route("Retailers/{search}")]
[HttpGet]
public Task<List<Lookup>> Retailers(string search)
{
    var user = UserManager.FindById(User.Identity.GetUserId());
    Guid userId = Guid.Parse(user.Id);

    var companies = _unitOfWork.GetRepository<Company>().GetAll().Where(c => c.CompanyType == CompanyType.Retail && 
                (c.UserID == null || c.UserID == userId) && c.CompanyName.StartsWith(search)).Take(5)
                .Select(x => new Lookup { Id = x.Id, Name = x.CompanyName }).ToListAsync();

    return companies;
}
like image 697
Steve Wash Avatar asked Mar 24 '26 05:03

Steve Wash


1 Answers

You are missing the async and the await keywords.

  1. Add async to the method signature.
  2. Add await to your call to _unitOfWork.GetRepository...ToListAsync()

Code:

[Route("Retailers/{search}")]
[HttpGet]
public async Task<List<Lookup>> Retailers(string search)
{
    var user = UserManager.FindById(User.Identity.GetUserId());
    Guid userId = Guid.Parse(user.Id);

    var companies = await _unitOfWork.GetRepository<Company>().GetAll().Where(c => c.CompanyType == CompanyType.Retail && 
                (c.UserID == null || c.UserID == userId) && c.CompanyName.StartsWith(search)).Take(5)
                .Select(x => new Lookup { Id = x.Id, Name = x.CompanyName }).ToListAsync();

    return companies;
}

As a reference here is a good link to asynchronous programming: Asynchronous Programming with Async and Await.

like image 100
Igor Avatar answered Mar 26 '26 18:03

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!