I am trying to insert multiple relational data into SQL server DB using EF core 5. I want to insert multiple parents with multiple child. Parents and child has one to many relationship. I am trying to add it using context.AddRang(lstparents) It is inserting child entity data only for one parents and for rest of the parents there is no entry. Could you please help me to resolve this issue.
My Models
Public class Parent
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Public int64 Id {get; set;}// this is identity column
Public string Name { get; set;}
Public List<Child> child { get; set;}
}
Public class Child
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Public int64 id { get; set;} // identity column
Public string ChildName { get; set;}
Public int64 ParentId { get; set;}
[Foreign key("ParentId")]
Public Parent parent { get; set;}
}
// Here is insertion logic
Public void main(string[] args)
{
List<Child> lstChild = new List<Child> ()
{
new Child{ ChildName= "Child1Name"},
new Child{ ChildName= "Child2Name"},
new Child{ ChildName= "Child3Name"}
};
List<Parent> lstparents = new List<Parent>()
{
new Parent {Name = "xyz", Child= lstChild },
new Parent {Name = "xyz1", Child= lstChild}
};
Context.AddRangeAsync(lstparents);
Context.SaveChangesAsync();
}
I have tried below options as well but I ran into another problem.
Option 1:
Public void main(string[] args)
{
List<Child> lstChild = new List<Child> ()
{
new Child{ ChildName= "Child1Name"},
new Child{ ChildName= "Child2Name"},
new Child{ ChildName= "Child3Name"}
};
List<Parent> lstparents = new List<Parent>()
{
new Parent {Name = "xyz", Child= lstChild },
new Parent {Name = "xyz1", Child= lstChild}
};
foreach(var item in lstparents)
{
Context.Add(item);
foreach(var child in lstChild)
{
Context.Add(child);
}
}
Context.SaveChangesAsync();
}
option2: In below line of code i am getting an error "Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF"
Public void main(string[] args) {
List<Child> lstChild = new List<Child> ()
{
new Child{ ChildName= "Child1Name"},
new Child{ ChildName= "Child2Name"},
new Child{ ChildName= "Child3Name"}
};
List<Parent> lstparents = new List<Parent>()
{
new Parent {Name = "xyz", Child= lstChild },
new Parent {Name = "xyz1", Child= lstChild}
};
foreach(var item in lstparents)
{
Context.Entry(item).State=EntityState.Added;
foreach(var child in lstChild)
{
Context.Entry(child).State=EntityState.Added;
}
}
Context.SaveChangesAsync();
}