簡體   English   中英

連接多對多模型以允許視圖迭代

[英]Joining many-to-many models to allow iteration in view

我正在使用以下模型:

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

使用此流利的API可以在FListItem上創建復合主鍵。

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添加控制器, FList創建以下腳手架

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

這使得fLists可以在索引視圖上進行迭代。

我需要做的是包括Items可通過每個迭代fList 我不能使用Include因為FList上沒有Items導航屬性。

我想我需要在fListJoin Items並創建一個帶有IEnumerable的viewModel以允許Items迭代。

請任何人告知以上推理是否正確,如果正確,請協助進行Join

您走在正確的軌道上。 如果創建視圖模型,則將為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; }
}

您還可以Include以下項目:

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

我不知道視圖模型是什么樣的,但是一個FList的項目可以通過FList方式進行迭代:

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

順便說一句,我更願意將兩個ICollection<FListItem>集合都命名為“ FListItem”,以免將它們分別與真實的ItemsFLists混淆。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM