Reputation: 145
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 :
Hello everyone, I have posted my answer below through which I was able to achieve the above requirement.
Upvotes: 0
Views: 448
Reputation: 145
I have been able to create the required tables with the required mappings, using the below entities and map files, using entity framework 6 code first approach.
public class Parent
{
public int ParentId {get; set;}
public Nullable<int> LastChildId{ get; set; }
public virtual ICollection<Child> Children{ get; set; }
public virtual Child LastChild { get; set; }
}
public class Child
{
public int ChildId {get;set;}
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
ParentMap.cs (Mapping File)
-----------
public class ParentMap : EntityTypeConfiguration<Entity.Parent>
{
public ParentMap()
{
this.HasOptional(h => h.LastChild)
.WithMany()
.HasForeignKey(h => h.LastChildId)
.WillCascadeOnDelete(false);
}
}
ChildMap.cs (Mapping File)
-----------
public class ChildMap : EntityTypeConfiguration<Entity.Child>
{
public ChildMap()
{
this.HasRequired(t => t.Parent)
.WithMany(t => t.Child)
.HasForeignKey(t => t.ParentId)
.WillCascadeOnDelete(false);
}
}
Upvotes: 0
Reputation: 334
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; }
}
Upvotes: 0