我想使用Entity Framework 6代码优先方法在下面的两个表中创建。我可以使用属性符号或流畅的API或两者结合使用。我主要想知道如何在两个实体之间创建映射,以便正确创建外键,并且每个实体(Icollection或对象)的虚拟属性将是什么样。
表名称-父级
+-------------+-------+-----------------------+
| ColumnName | Type | Constraint |
+-------------+-------+-----------------------+
| ParentId | int | Primary Key |
| LastChildId | int | Foreign Key, Nullable |
+-------------+-------+-----------------------+
Note- LastChildId列包含最后一个ChildId(如果有子代),对应于parent表中的ParentId,否则为NULL。
表名称-子
+------------+-------+----------------------+
| ColumnName | Type | Constraint |
+------------+-------+----------------------+
| ChildId | int | Primary Key |
| ParentId | int | ForeignKey, Not Null |
+------------+-------+----------------------+
示例
[Table-父级
+----------+-------------+
| ParentId | LastChildId |
+----------+-------------+
| 1 | Null |
| 2 | 1 |
| 3 | 3 |
+----------+-------------+
表-子
+---------+----------+
| ChildId | ParentId |
+---------+----------+
| 1 | 2 |
| 2 | 3 |
| 3 | 3 |
+---------+----------+
其他信息:
public class Child
{
public int ChildID { get; set; }
public int ParentID { get; set; } //this is to name your key properly,
//can be omitted, but EF will create field
//with name smth like Parent_ParentId
public virtual Parent Parent { get; set; } // **one**-to-many
}
public class Parent
{
public int ParentId { get; set; }
public virtual ICollection<Child> Child { get; set; } //one-to-**many**
public int LastChildID { get; set; }
}