Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 852
globetrotter Avatar asked Oct 30 '14 01:10

globetrotter


1 Answers

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();        
    }
}
like image 145
sa_ddam213 Avatar answered Oct 03 '22 06:10

sa_ddam213