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
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With