C # async on LINQ return

I just realized 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();        
        }
    }

      

... won't work as async methods can't expect LINQ expressions. I did some searching but I managed to find some tricky solutions.

How are functions returning LINQ expressions converted to asynchronous versions?

+3


source to share


2 answers


Add namespace System.Data.Entity

and use extension methodsAsync

ToListAsync

Should do the trick in this case



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();        
    }
}

      

+8


source


Technically, this method doesn't return a lambda. He returns List<Review>

.

This is what you posted will not compile. But this:



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

      

If that doesn't answer your question, maybe you can be clearer about what exactly you are trying to accomplish, and why the above doesn't.

+4


source







All Articles