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.- https://codereview.stackexchange.com/questions/32160/filtering-a-collection-by-an-async-result
- Filtering a collection by an async result, built an extension method called WhereAsync.
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);
}
- https://forums.asp.net/t/1978783.aspx?Running+LINQ+to+SQL+query+async+
Running LINQ to SQL query async
- Wrap with a task, Task.Run(() => { }
- https://www.c-sharpcorner.com/UploadFile/4b0136/working-with-asynchronous-programming-with-entity-framework/
- public async static Task<List<Student>> GetAllStudentsAsync(){MyDatabaseEntities db = new MyDatabaseEntities();var query = from item in db.Studentsselect item;return await query.ToListAsync();}