Use of Include with async await

19,550

Solution 1

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);

Solution 2

Followed by @Anthony and @Korayem answer, I recommend to do as below for safer code.

Item item = await db.Items.Include(o => o.Tags).FirstOrDefaultAsync(i => i.Id == id);

if(item == default(Item))
    return NotFound();
Share:
19,550
B-Lat
Author by

B-Lat

Software engineer currently working in education sector. Specialising in web applications written in Microsoft stack, namely ASP.NET, MVC, SQL Server, WCF, HTML, CSS, blah blah blah....

Updated on June 07, 2022

Comments

  • B-Lat
    B-Lat almost 2 years

    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

  • B-Lat
    B-Lat about 10 years
    Thanks very much. Clear and concise answer. Great!
  • IDIR Samir
    IDIR Samir over 7 years
    Note performance diff between Single() vs First() where former looks finds record and then keeps looking to check if another exists while latter returns upon hitting the record