2014-12-06 61 views
1

迭代我使用这些模型:加入许多一对多模式,允许在视图

public class FList 
{ 
    public int FListID { get; set; } 
    public string Title { get; set; } 
    public int UserID { get; set; } 
    public DateTime Posted { get; set; } 
    public virtual User User { get; set; } 
    public ICollection<FListItem> Items { get; set; } 
} 

public class Item 
{ 
    public int ItemID { get; set; } 
    public string Name { get; set; } 
    public ICollection<FListItem> FLists { get; set; } 
} 

public class FListItem 
{ 
    public int FListID { get; set; } 
    public int ItemID { get; set; } 
    public int Score { get; set; } 
    public virtual FList FList { get; set; } 
    public virtual Item Item { get; set; } 
} 

public class User 
{ 
    public int UserID { get; set; } 
    public string UserName { get; set; } 
    public ICollection<FList> FLists { get; set; } 
} 

与上创建FListItem复合主键此流利的API。

modelBuilder.Entity<FaveListItem>().HasKey(fi => new { fi.FaveListID, fi.ItemID }); 

modelBuilder.Entity<FList>() 
      .HasMany(f => f.Items) 
      .WithRequired(fi => fi.FList) 
      .HasForeignKey(fi => fi.FListID); 
modelBuilder.Entity<Item>() 
      .HasMany(f => f.FLists) 
      .WithRequired(fi => fi.Item) 
      .HasForeignKey(fi => fi.ItemID); 

如果我添加控制器,用于FList,下面的脚手架创建

public ActionResult Index() 
{ 
    var fLists = db.FLists.Include(f => f.User); 
    return View(fLists.ToList()); 
} 

其允许fLists要在索引视图迭代。

我需要做的是包括Items可以迭代通过每个fList。我无法使用Include,因为FList上没有Items导航属性。

我想我需要在fListJoinItems,并创建一个视图模型与一个IEnumerable允许的Items迭代。

请有人建议,如果上述推理是正确的,如果是这样,请协助Join

回答

1

您也可以Include项目:

db.FLists.Include(f => f.User) 
     .Include(f => f.Items.Select(i => i.Item)) 

我不知道是什么视图模型的样子,但项目一个FList可迭代

fList.Items.Select(i => i.Item) 

顺便说一句,我宁愿命名b其他收藏“FListItem”,以免将它们分别与真实的ItemsFLists混淆。

1

你在正确的轨道上。如果您创建视图模型,则需要将导航属性指定给Flist viewmodel类中的项目。完成之后,您无需对包含进行修改,它只会自动提供。

你视图模型看起来像......

public class FList 
{ 
[Key] 
    public int FListID { get; set; } 
    public string Title { get; set; } 
    public int UserID { get; set; } 
    public DateTime Posted { get; set; } 
    public virtual User User { get; set; } 


    public virtual ICollection<Item> Items { get; set; } 

} 

public class Item 
{ 
[Key] 
    public int ItemID { get; set; } 
    public string Name { get; set; } 
    public ICollection<FListItem> FLists { get; set; } 
}