Entity Framework 6 .FindAsync() with .Include()

c# entity-framework entity-framework-6 linq


I'm new to the Async() world of EF and I was wondering if this was possible. My Google searches rendered no answers.

I have two classes:

public class User {
    public int Id { get; set; }
    public string Name { get; set; }

public class Application {
    public int Id { get; set; }
    public string Description { get; set; }

    public int UserId { get; set; }
    public User User { get; set; }

My Details route for Application is as follows:

public async Task<ActionResult> Details(int? id) {
    if (id == null) {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    Application application = await db.Applications.FindAsync(id);
    if (application == null) {
        return HttpNotFound();
    return View(application);

The code above for details returns null for application.User.Name

I've seen calls to get the foreign object data like db.Applications.Include(a => a.User). How can I combine both of these? Or maybe something other than .include() is to used here.


9/1/2014 3:29:37 PM

Accepted Answer

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);
2/16/2014 10:55:45 PM

Popular Answer

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

Related Questions


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