0

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; }
}
5
  • Can you post your model? Assuming you have related entities, you can use .Include() to load related entities (Eager Loading). Or if you just access a navigation property, it will use lazy loading. Commented Feb 19, 2014 at 12:24
  • Isn't that what I'm already doing in my DisplayFor line? (accessing the navigation property) Commented Feb 19, 2014 at 12:31
  • I have added the model Commented Feb 19, 2014 at 12:33
  • I've testing "just accessing" the navigation property, it simply does not work Commented Feb 19, 2014 at 13:43
  • Put a stop before rendering the View and see if your model if being loaded correctly. Commented Feb 19, 2014 at 14:21

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

7 Comments

This is my linq query: db.MyEntities.FindAsync(id). If I add Include(User) then I can't FindAsync() anymore, I guess I could always resort to Single() but is this really the right way of doing this? It's strange that I have to change the FindAsync() pattern just to include related entities.
try using SingleOrDefaultAsync()
Also, will it load the users for every MyEntity or just for the found entity?
it will load the single "User" entity that is attached to the MyEntity model
and make sure you use Include("User") with quotes
|
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.