Entity Framework: ToListAynsc & WhereAsync

When upgrading aspnet mvc applications I like to take a look on how I can convert the api's to async. This sometimes is really easy but as things get more complex my queries do as well. So this is a list of ways you can form a where clause on top your async but note not all solutions take advantage of it.

Entity Framework Core provides a set of asynchronous extension methods that can be used as an alternative to the LINQ methods that cause a query to be executed and results returned. Examples include ToListAsync()ToArrayAsync()SingleAsync(), etc. There are not async versions of LINQ operators such as Where(...)OrderBy(...), etc. because these methods only build up the LINQ expression tree and do not cause the query to be executed in the database.
public static async Task<IEnumerable<T>> WhereAsync2<T>(this IEnumerable<T> items, Func<T, Task<bool>> predicate)
    var itemTaskList = items.Select(item=> new {Item = item, PredTask = predicate.Invoke(item)}).ToList();
    await Task.WhenAll(itemTaskList.Select(x=>x.PredTask));
    return itemTaskList.Where(x=>x.PredTask.Result).Select(x=>x.Item);
  • Notes when looking at "include" in the docs they also don't show example with async...

    Popular posts from this blog

    Installing Windows on Acer chromebook 15 cb3-532

    CSharp Cheatsheet