I'm building a simple app to learn Entity Framework, roughly following this and this tutorials.
I've successfully code-first created my tables, I can query them and see the expected data and the correct keys for my one-to-many relationship with my seeded data.
public class Organization
{
public Organization()
{
Members = new HashSet<Member>();
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Member> Members { get; set; }
}
public class Member
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID { get; set; }
public string Name { get; set; }
public string Note { get; set; }
public Guid OrganizationID { get; set; }
public virtual Organization Organization { get; set; }
}
public class OrganizationMemberContext : DbContext
{
public OrganizationMemberContext(DbContextOptions<OrganizationMemberContext> options) : base(options)
{
}
public DbSet<Organization> Organizations { get; set; }
public DbSet<Member> Members { get; set; }
}
I continued on to create a scaffolded controller for the Organization
model using the OrganizationMemberContext, and that works beautifully. CRUD operations appear to be operating as expected.
I then wanted to display each organization's list of members under that organization on the index page. However... what I think should work returns no related data.
public async Task<IActionResult> Index()
{
_context.Organizations.Include(x => x.Members);
return View(await _context.Organizations.ToListAsync());
}
I get the list of Organizations, but each Organization's Members property is empty in the Model sent to the page (confirmed watching locals in VS).
Again, the seeded data is being inserted correctly: I can see in the DB where Organization.ID values precisely match Member.OrganizationID values as expected.
Original code
public async Task<IActionResult> Index()
{
_context.Organizations.Include(x => x.Members); // use include with no additional queries
return View(await _context.Organizations.ToListAsync()); // made a new query - it knows nothing about include part - Lazy loading still in effect
}
Should be:
public async Task<IActionResult> Index()
{
return View(await _context.Organizations.Include(x => x.Members)ToListAsync()); // query see include and add this information in the result
}