0
votes

I have a Web API (not .core web API) method uses Entity Framework to return some records from the database. The result is IEnumerable Model and I would like to modify it to use Async/Await technique to improve the performance, but I don't know how! I tried to use ToListAsync but it did not work.

My Web API method code

[HttpGet]
[Route("api/student/{id}/")]
public IEnumerable<Student> Get(int id)
{            
    try
    {
        var db = new DBEntities();
        return db.GetStudentDetails(id);
    }
    catch(Exception exception)
    {
        _logger.Error(exception.Message);
        throw new HttpResponseException(HttpStatusCode.ExpectationFailed);
    }
}

My Entity Framework function code:

public virtual ObjectResult<Student> GetStudentDetails(int id)
{
     var idParameter = id.HasValue ?
            new ObjectParameter("id", id) :
            new ObjectParameter("id", typeof(int));

        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Student>("sp_get_student_details", idParameter);
 }

Thanks in advance.

1
Can you explain your reasoning why this method but async should be more performant? - MindSwipe
Coz, it could be hit by multiple users at the same time. - Daina Hodges
ASP.NET (both core and framework) start a new process for every distinct call to a web API, therefore each users request will be handled in parallel, making this async will not change it - MindSwipe
have a look to this question stackoverflow.com/questions/48159449/… - nzrytmn
Thanks, I did not know that. - Daina Hodges

1 Answers

-2
votes

This should do the trick

public virtual async Task<ObjectResult<Student>> GetStudentDetails(int id)
{
      var idParameter = id.HasValue ?
      new ObjectParameter("id", id) :
      new ObjectParameter("id", typeof(int));

      return await ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Student>("sp_get_student_details", idParameter);
}