Let's say I have the following method:
var result = (await db.Students
.Where(s => s.Name == "Foo")
.ToListAsync())
.Select(s => MySuperSmartMethod(s));
MySuperSmartMethod
here is a method that cannot be translated to SQL.
As I understood from this answer, calling the ToList()
(and ToListAsync()
as well) method to evaluate future methods on the client side has a problem: it immediately queries the database, iterates the result and puts it into memory.
So, it is better to call AsEnumerable()
instead of ToList()
, cause it does not create an unnecessary intermediate list. AsEnumerable()
returns an IEnumerable
, so when it comes to executing future methods, they will iterate over objects directly in the IEnumerable.
Therefore I conclude that I should rewrite the previous method to something something like this:
var result = db.Students
.Where(s => s.Name == "Foo")
.AsEnumerable()
.Select(s => MySuperSmartMethod(s));
Ok, but now I have another problem: my method is not asynchronous anymore.
So, what should i do? Are there any other approaches? Does asynchronous quering database lead to any performance benefits in an ASP.NET Core application? Or should I rewrite my asynchronous MediatR queries and commands to synchronous replacing ToListAsync()
with AsEnumerable()
wherever it's possible?