Code sample without using async:
var products = db.Products.Where(_ => _.UserId == currentUserId);
How do I make this query asynchronous taking into account that Where
of Linq
does not support the use of await
?
Code sample without using async:
var products = db.Products.Where(_ => _.UserId == currentUserId);
How do I make this query asynchronous taking into account that Where
of Linq
does not support the use of await
?
The trick is to compose the list:
var products = await db.Products.Where(_ => _.UserId == currentUserId).ToListAsync();
See all asynchronous methods by this link here .
The Where
method constructs an object representing a query to be executed, and no query has been executed yet. So it makes no sense for the Where
method to be executed asynchronously .
What you should be looking for is the asynchronous execution of the method that actually executes the query. These methods are said to materialize the query. An example is the ToList
method, which transforms the object representing the query into a list of materialized objects.
The ToList
method has a version that can be called asynchronously: ToListAsync
, which allows the use of the keyword async
which will materialize objects asynchronously.
// criando objeto que representa uma query, mas que não executa a mesma
var productsQuery = db.Products.Where(_ => _.UserId == currentUserId);
// materializando a query, ou seja, obtendo os resultados, de forma assíncrona
var products = await productsQuery.ToListAsync();
As additional information, you can also do this at the time of saving the data. The SaveChanges
method also has an asynchronous alter-ego SaveChangesAsync
:
// salvando as alterações feitas no context
db.SaveChangesAsync();