简体   繁体   English

缺少具有一对多关系的子元素

[英]Missing Child Elements With One-To-Many Relationship

In my code I'm getting back a List<TableA>在我的代码中,我得到了一个List<TableA>

TableA class definition表A class定义

class TableA {

        public int ID { get; set; }
        public virtual List<Child>? Children{ get; set; }

}

Child table has 2 columns: TableAID, and TableBID.子表有 2 列:TableAID 和 TableBID。 The PK is a composite key referencing both of these columns. PK 是引用这两个列的复合键。 TableAID is a FK referencing dbo.TableA.ID and TableBID is a FK referencing dbo.TableB.ID TableAID 是引用 dbo.TableA.ID 的 FK,而 TableBID 是引用 dbo.TableB.ID 的 FK

Child class definition:子 class 定义:

class Child
    {
        public int TableAID { get; set; }

        public int TableBID { get; set; }

        public virtual TableA TableA { get; set; }

    }

Child table data:子表数据:

TableAID桌辅助 TableBID表BID
1 1 4 4
1 1 5 5
2 2 4 4

This is my model setup code:这是我的 model 设置代码:

modelBuilder.Entity<Child>()
                .HasKey(c=> new { c.TableAID, c.TableBID  });


            modelBuilder.Entity<TableA>()
               .HasKey(a => a.ID);

            modelBuilder.Entity<TableA>()
                .HasMany(a => a.Children)
                .WithOne(a => a.TableA)
                .HasForeignKey(a => a.TableAID);

When I retrieve the list of type TableA , I'm getting back 2 TableA elements.当我检索TableA类型的列表时,我得到了 2 个 TableA 元素。 For the first element, TableA of ID 1, the Children property has 2 elements in it, which is working as designed.对于第一个元素,ID 为 1 的 TableA,Children 属性中有 2 个元素,它们按设计工作。 But for the second element, Table A of ID 2, I get back no child elements (empty list), even though there exists a child element that has a TableAID of 2. I can't figure out why this is happening.但是对于第二个元素,ID 为 2 的表 A,我没有返回任何子元素(空列表),即使存在一个 TableAID 为 2 的子元素。我不知道为什么会这样。 Does anyone have any advice?有人有建议吗?

all together should be like this在一起应该是这样的

class TableA {

        public int ID { get; set; }
        public virtual List<Child> Children{ get; set; }

}

class TableB {

        public int ID { get; set; }
        public virtual List<Child> Children{ get; set; }

}

class Child
    {
        public int TableAID { get; set; }

        public int TableBID { get; set; }

        public virtual TableA TableA { get; set; }
        public virtual TableB TableB { get; set; }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM