Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Include with async await

I have an EF query in which I am returning an 'Item' by it's unique identifier. I'm using the scaffolded controller provided by MVC and this works ok, but now I want it to return a list of tags which belong to the item.

I thought I might be able to use 'Include' as shown below to eager fetch the tags. However this does not seem to be allowed when using async.

Item item = await db.Items.Include("Tags").FindAsync(id); 

Can anybody explain why this won't work and suggest an alternative way to bring back the item's tags?

Cheers

Ben

like image 292
B-Lat Avatar asked Feb 16 '14 22:02

B-Lat


People also ask

Should I use async with EF core?

Generally speaking, if there are asynchronous APIs, then you should use them for new code. Asynchronous code frees up the calling thread. If your application is a GUI application, this can free up the UI thread; if your application is a server application, this can free up threads to handle other requests.

What's the point of async await?

Note: The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async / await is similar to combining generators and promises. Async functions always return a promise.

Is Linq asynchronous?

Note that there are no async versions of some LINQ operators such as Where or OrderBy, because these only build up the LINQ expression tree and don't cause the query to be executed in the database. Only operators which cause query execution have async counterparts.

What is one benefit of using async await?

The biggest advantage of using async and await is, it is very simple and the asynchronous method looks very similar to a normal synchronous methods. It does not change programming structure like the old models (APM and EAP) and the resultant asynchronous method look similar to synchronous methods.


1 Answers

Find() and FindAsync() are methods on type DbSet (which is what db.Items is). Include() returns a DbQuery object, which is why FindAsync() is not available. Use SingleOrDefaultAsync() to do the same thing as FindAsync() (the difference is it will go straight to the database and won't look in the context to see if the entity exists first)...

Item item = await db.Items.Include("Tags").SingleOrDefaultAsync(i => i.Id == id); 
like image 197
Anthony Chu Avatar answered Sep 18 '22 16:09

Anthony Chu