LINQ Interview Question #145
How can LINQ be used with asynchronous EF Core queries?
Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
EF Core provides asynchronous terminal operations such as ToListAsync, FirstOrDefaultAsync, AnyAsync, CountAsync, and SumAsync. They asynchronously wait for database I/O.
Detailed Explanation
EF Core provides asynchronous terminal operations such as ToListAsync, FirstOrDefaultAsync, AnyAsync, CountAsync, and SumAsync. They asynchronously wait for database I/O.
The query composition itself is still normally synchronous; asynchronous behavior becomes relevant when the database operation is executed.
Code Example
var products = await db.Products
.Where(p => p.IsActive)
.OrderBy(p => p.Name)
.ToListAsync(cancellationToken);
bool exists = await db.Products
.AnyAsync(p => p.Stock > 0, cancellationToken);