globetrotter globetrotter -4 years ago 131
C# Question

c# async when returning LINQ

I've just realised that this code:

public async Task<List<Review>> GetTitleReviews(int titleID)
{
using (var context = new exampleEntities())
{
return await context.Reviews.Where(x => x.Title_Id == titleID).ToList();
}
}


...will not work as async methods cannot await LINQ expressions. I've did some searches but only managed to find some overcomplicated solutions.

How should functions which return LINQ expressions be converted to async versions?

Answer Source

Add the System.Data.Entity namespace and take advantage of the Async extension methods

In this case ToListAsync should do the trick

using System.Data.Entity;

public async Task<List<Review>> GetTitleReviews(int titleID)
{
    using (var context = new exampleEntities())
    {
        return await context.Reviews.Where(x => x.Title_Id == titleID).ToListAsync();        
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download