I want to create below two tables using Entity Framework 6 code first approach. I can use attribute notation or fluent API or combination of both.
Mainly I want to know how to create the mappings between the two entities, so that the foreign keys get created properly and what will be the virtual property be like in each entity (Icollection or object).
Table Name - Parent
+-------------+-------+-----------------------+
| ColumnName | Type | Constraint |
+-------------+-------+-----------------------+
| ParentId | int | Primary Key |
| LastChildId | int | Foreign Key, Nullable |
+-------------+-------+-----------------------+
Note- LastChildId column contains the last ChildId, if there is a child, corresponding to a ParentId in parent table else NULL.
Table Name - Child
+------------+-------+----------------------+
| ColumnName | Type | Constraint |
+------------+-------+----------------------+
| ChildId | int | Primary Key |
| ParentId | int | ForeignKey, Not Null |
+------------+-------+----------------------+
Example
Table - Parent
+----------+-------------+
| ParentId | LastChildId |
+----------+-------------+
| 1 | Null |
| 2 | 1 |
| 3 | 3 |
+----------+-------------+
Table - Child
+---------+----------+
| ChildId | ParentId |
+---------+----------+
| 1 | 2 |
| 2 | 3 |
| 3 | 3 |
+---------+----------+
Additional Information :
- A parent can have multiple child associated with it i.e. one to many mapping (parent to child). Child Virtual property should be ICollection.
- One child can have only one parent associated with it i.e. one to one mapping (child to parent).
Hello everyone, I have posted my answer below through which I was able to achieve the above requirement.