Entity Framework child objects not populating

entity-framework entity-framework-6

Question

When I run the website in the debugger, my simple model doesn't get properly populated by the entity framework.

Simple is the model:

public class Team
{
    /// <summary>
    ///     Constructor required for the EntityFramework to create the object.
    /// </summary>
    private Team()
    {            
    }

    public Team(string name, ApplicationUser owner)
    {
        Name = name;
        Owner = owner;
    }

    [Required]
    public int Id { get; private set; }

    [Required]
    public string Name { get; private set; }

    [Required]
    public ApplicationUser Owner { get; private set; }

    [Required]
    public List<TeamMembership> Members { get; set; }
}


public class TeamMembership
{
    /// <summary>
    ///     Constructor for the EntityFramework
    /// </summary>
    private TeamMembership()
    {
    }

    public TeamMembership(ApplicationUser user, MembershipStatus status)
    {
        User = user;
        Status = status;
    }

    [Required]
    public ApplicationUser User { get; private set; }

    [Required]
    public MembershipStatus Status { get; set; }

    [Required]
    public int Id { get; private set; }
}

Where ApplicationUser is the default class produced by the membership infrastructure of ASP MVC 5.

The entity framework appropriately populates my Team and the Owner when I run my tests (Specflow), which build a new LocalDb database with a unique id for each test and runs the migrations on that db.

However, my Team is not completely populated when I utilize the website and attempt to connect with the program because the Owner isnull and Members is uninhabited. However, the owner ID is appropriately established in the database, and the query appears to be valid. The test's query execution and the app's operation appear to be identical.

How do I begin to debug the problem and why may this be the case?

I feel as though I am overlooking something obvious.

1
5
2/6/2014 8:07:59 PM

Accepted Answer

Probably necessary to include.Include() to your question, which is not indicated in your inquiry but should resemble this:

var query = context.Teams.Include(x => x.Owner).Include(x => x.Members).Where( ... );

Until they are required, EF will only load the top-level entities and not the ones it references (lazy loading). Simply attempting to access those navigation properties should cause them to load from the database if the context hasn't been disposed of, but this won't happen if it has.

.Include() will notify EF that the referring entity must be eagerly loaded along with those navigation attributes.

For more information on lazy/eager loading and how to manage it, see this MSDN website.

11
6/17/2016 7:43:13 PM


Related Questions





Related

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