I have a parent/child hierarchy of which I want to insert a new parent into a DbContext and have it automatically persist the child objects.
Every time I all SaveChanges on DbContext EF is throwing an exception of
Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.
I understand the error as the Child object doesn't have a Identity column.
Models are as follows:
public class Parent
{
public int ParentId { get; set; }
public string Name { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
public string Name { get; set; }
}
Mapping for the Child object below::
public class ChildMap : EntityTypeConfiguration<Child>
{
this.HasKey(p => p.ParentId);
this.Property(p => p.ParentId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.HasRequired(t => t.Parent)
.WithMany(t => t.Children)
.HasForeignKey(d => d.ParentId);
}
The models were generated using EF Power tools as we are following DB-First design.
Is there a way saving the graph instead of saving the parent first then child?