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

c# entity-framework entity-framework-6 linq


Being new to theAsync() I pondered whether this was feasible in the world of EF. My Google searches came up empty.

I'm taking 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 path forApplication the following:

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 more information yieldsnull for application.User.Name

I've heard requests for the foreign object information, such asdb.Applications.Include(a => a.User) . How do I merge these two? or perhaps something different from.include() to be used in this.


9/1/2014 3:29:37 PM

Accepted Answer

Find() and FindAsync() techniques on typeDbSet (That is what)db.Items is). Include() provides aDbQuery hence; objectFindAsync() is not offered. UseSingleOrDefaultAsync() to act similarly toFindAsync() (The difference is that it won't first check the context to determine if the entity already exists; instead, it will proceed directly to the database.)

Item item = await db.Items.Include("Tags").SingleOrDefaultAsync(i => i.Id == id);
2/16/2014 10:55:45 PM

Popular Answer

After @Anthony and @Korayem's responses, I advise doing as follows 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