Luis Ferrao
Luis Ferrao

Reputation: 1503

Lazy loading not working when trying to access related entity

This is microsoft's scaffolding code for the action Details of the entity MyEntity:

public async Task<ActionResult> Details(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    MyEntity myEntity = await db.MyEntities.FindAsync(id);
    if (myEntity == null)
    {
        return HttpNotFound();
    }
    return View(myEntity);
}

Now let's say I want to display the name of the owner of this entity in details.cshtml, if I write the following code:

<dt>
    Owner
</dt>
<dd>
    @Html.DisplayFor(m => m.User.FullName)
</dd>

User shows up as null, even after trying to access Model.User to trigger the lazy loading.

Edit: Adding the model as requested

public class MyEntity
{
    public Guid? Id { get; set; }
    public string Name { get; set; }
    public ApplicationUser User { get; set; }
}

Upvotes: 0

Views: 1469

Answers (2)

brandera33
brandera33

Reputation: 21

I was running into the same issue, and Matt's answer led me down a similar road. I thought I'd share what I found.

This article indicates that Lazy Loading doesn't fit well with the Async pattern. Good to know.

With that, I looked into eager loading. I found my answer there.

MyEntity myEntity = await db.MyEntities.Where(m => m.Id == id)
                                       .Include(m => m.User)
                                       .FirstOrDefaultAsync();

Hope that helps someone else!

Upvotes: 0

Matt Tabor
Matt Tabor

Reputation: 1053

Add .Include("User") to your linq query.

Upvotes: 1

Related Questions