Why are queries that modify database data awaitable, while queries that only read data not?

async-await asynchronous c# entity-framework-core

Question

I can asynchronously write new rows to the database:

await dbContext.Chatlogs.AddAsync(new ChatMessage(messageString, time, author));
await dbContext.SaveChangesAsync();

But what about just reading content from the databse?

string firstMessageEverPosted = dbContext.Chatlogs.OrderBy(msg => msg.time).First().content;

No await here. And inserting await causes compilation errors:

string doesntWork = await dbContext.Chatlogs.OrderBy(msg => msg.time).First().content;

Am I missing something or is it not possible to asynchronously read content from the database? If so, I'm curious what is so fundamentally different with just reading content that it was not deemed useful to allow doing this asynchronously?

1
1
8/27/2018 11:59:41 AM

Accepted Answer

Because First just is not asynchronous. Try FirstAsync instead:

string works = (await dbContext.Chatlogs.OrderBy(msg => msg.time).FirstAsync()).content;
6
8/27/2018 11:53:03 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow