【问题标题】:Entity Framework one-to-many Configuration实体框架一对多配置
【发布时间】:2014-12-22 18:07:36
【问题描述】:

我目前有以下数据库结构:

  • TableA (itemCode int, itemCategoryCode int, itemDescription description)
  • TableB (id int, itemCode int, itemCategoryCode int)

TableA 的 PK 是 (itemCode, itemCategoryCode)。 TableB的PK是id,FK是(itemCode, itemCategoryCode)

我需要设置 EF,以便在 TableA 和 TableB 之间建立一对多的关系。这样当我从 TableB 中抓取对象时,就会填充 TableA 的导航属性。

如何使用注释设置我的 POCO 类以实现此和/或流畅的 API?

谢谢。

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    带有数据注释:

    表 A:

    public class TableA {
    
      [Key, Column(Order=0)]
      public int itemCode { get; set; }
    
      [Key, Column(Order=1)]  
      public int itemCategoryCode { get; set; }
    
      public virtual ICollection<TableB> TableBs { get; set; }
    }
    

    表B:

    public class TableB {
    
      [Key]
      public int ID { get; set; }
    
      [ForeignKey("TableARecord"), Column(Order=1)]
      public int itemCode { get; set; }
    
      [ForeignKey("TableARecord"), Column(Order=2)]  
      public int itemCategoryCode { get; set; }
    
      public virtual TableA TableARecord { get; set; }
    
    }
    

    【讨论】:

    • 当我应用注释时它起作用了。但是,当我在其他表上加入它并从上下文中带回对象时,不会填充该属性。我错过了什么吗?
    【解决方案2】:

    只需向“Many”类添加一个虚拟收藏属性, 和你的“许多”类的“一”类型的属性 请参阅下面来自http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx的代码

    public class Student
        {
            public Student() { }
    
            public int StudentId { get; set; }
            public string StudentName { get; set; }
    
            public virtual Standard Standard { get; set; }
        }
    
        public class Standard
        {
            public Standard()
            {
                StudentsList = new List<Student>();
            }
            public int StandardId { get; set; }
            public string Description { get; set; }
    
            public virtual ICollection<Student> Students { get; set; }
        }
    

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多