簡體   English   中英

Code First Entity Framework不會創建一對多關系

[英]Code First Entity Framework doesn't create one to many relationship

因此,我有一個班級(文章)應該與另一個班級(類別)具有一對多關系:

public class Article
{
  [Key]
  public int ArticleId { get; set;}

  public virtual List<Category> Categories { get; set; }
}

public class Category
{
  [Key]
  public int Id { get; set;}

  public string Caption { get; set;
}

當我使用Code First構建數據庫時,它生成的類別與Article具有一對一的關系。 這導致類別僅與單個條款相關。 刪除並重新創建數據庫仍然會產生問題。 關於我在做什么錯的任何想法嗎?

1)如果您的Article有很多Category ,但是Categories只有一個Article

public class Article{
    private ICollection<Category> _CategoryList;
    public int ArticleId { get; set;}
    public virtual ICollection<Category> CategoryList {
        get { return _CategoryList = _CategoryList?? new HashSet<Category>(); }
        set { _CategoryList= value; }
    }
}

public class Category{
    public int Id { get; set;}
    public string Caption { get; set;}
    public Article Article { get; set;}
}

這對我來說聽起來有點不合邏輯。

2)如果您的Category有很多Article ,而Article中只有一個Category

public class Article{
    public int ArticleId { get; set;}
    public Category Category { get; set;}
}

public class Category{
    private ICollection<Article> _ArticleList;
    public int Id { get; set;}
    public string Caption { get; set;}
    public virtual ICollection<Article> ArticleList {
        get { return _ArticleList= _ArticleList?? new HashSet<Article>(); }
        set { _ArticleList= value; }
    }
}

注意,如果屬性名稱中有關鍵字Id ,則不需要[Key] EF會自動將該屬性視為Key

暫無
暫無

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

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