2017-06-27 76 views
1

我正在構建一個簡單的應用程序來學習實體框架,大致遵循thisthis教程。實體框架腳手架和相關數據

我已經成功完成代碼創建我的表格,我可以查詢它們並查看預期數據和與我的種子數據的一對多關係的正確密鑰。

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值與預期的一致的Member.OrganizationID值。

+3

這可能會爲你工作: 公共異步任務指數(){ 回報 視圖(AWAIT _context.Organizations.Include (x =>。Members).ToListAsync()); } – Sarbanjeet

+1

嘗試在查詢中包含其自身。 _context.Orgranizations.Include(X => x.Members).ToListASync()); – uk2k05

+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 
}