簡體   English   中英

如何直接以任意多關系EF6獲取“子”行

[英]How to get “child” rows directly in any to many relationship EF6

我有EF6模型,具有許多這樣的關系(我簡化了模型以使其更加清晰):

 public class Card 
 {
    public int CardId { get; set; }
    public string CardTitle { get; set; }

    public virtual ICollection<CardLayout> CardLayouts { get; set; }
 }

 public class Layout
 {
    public int LayoutId { get; set; }
    public string LayoutTitle { get; set; }

    public virtual ICollection<CardLayout> CardLayouts { get; set; }
 }

 public class CardLayout // relationship table
 {
    public int CardLayoutId { get; set; }
    public int CardId { get; set; }
    public int LayoutId { get; set; }

    public int CardLocation { get; set; }

    public virtual Card Card { get; set; }
    public virtual Layout Layout { get; set; }
 }

我現在是這樣使用的:

 int exampleId = 23;
 using (MyContext ctx = new MyContext())
 {
     Card c = ctx.Cards.Find(23);

     foreach (CardLayout cardLayout in c.CardLayouts)
     {
          Layout layout = cardLayout.Layout;
          DoSomethingWithLayout(layout);
     }
 }

我需要直接在Card對象內部放置Layout集合。 我不想通過關系表。 我想這樣使用它:

 int exampleId = 23;
 using (MyContext ctx = new MyContext())
 {
     Card c = ctx.Cards.Find(23);

     foreach (Layout layout in c.Layouts)
     {
          DoSomethingWithLayout(layout);
     }
 }

我已經嘗試過這樣的事情:

public class Card 
{
    public int CardId { get; set; }
    public string CardTitle { get; set; }

    public virtual ICollection<CardLayout> CardLayouts { get; set; }
    public virtual ICollection<Layout> Layouts { get; set; }
 }

但是Layouts集合始終為空。

我的問題是:如何直接從Card對象訪問Layouts集合? 我也想保留Card.CardLayouts集合,因為我的CardLayouts表包含字段(如簡化示例中的CardLocation)

附言 有人可以改善我的問題標題嗎? 我的英語不夠好,無法寫得更好。 提前致謝。

雖然我認為@Biscuits的評論是正確的。 如果您出於某種原因不想走那條路,那么您應該只能使用吸氣劑創建另一個屬性。

 public class Card 
 {
    public int CardId { get; set; }
    public string CardTitle { get; set; }

    public virtual ICollection<CardLayout> CardLayouts { get; set; }

    [NotMapped]
    public IEnumerable<Layout> Layouts
    {
       get
       {
         return this.CardLayouts.Select(cl => cl.Layout);
       }
    }
 }

暫無
暫無

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

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