我正在构建一个简单的应用来学习实体框架,大致遵循this和this教程。
我已经成功地代码优先创建了我的表,我可以查询它们并查看我的种子数据与我的一对多关系的预期数据和正确的密钥。
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; }
}
我继续使用OrganizationMemberContext为Organization
模型创建一个脚手架控制器,并且效果很好。 CRUD操作似乎按预期运行。
然后,我想在索引页面上显示该组织下每个组织的成员列表。但是......我认为应该工作的东西不会返回相关数据。
public async Task<IActionResult> Index()
{
_context.Organizations.Include(x => x.Members);
return View(await _context.Organizations.ToListAsync());
}
我获取了组织列表,但是每个组织的成员属性在发送到页面的模型中都是空的(确认在VS中观看本地人)。
再次,正确插入种子数据:我可以在DB中看到Organization.ID值与预期的Customer.OrganizationID值精确匹配。
答案 0 :(得分:1)
原始代码
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
}
应该是:
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
}