0

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?

gnaungayan
  • 522
  • 1
  • 9
  • 22

1 Answers1

1

I had a similar issue, which was resolved by removing unnecessary FK associations from the Model. For some reason, these weren't removed when updating the model from the database.

To do this, I simply found the association in the Entity Designer, removed it, and re-updated the model from the database.

It can also be caused by having invalid relationship multiplicities on a particular column, i.e. a 0..1 - 1 relationship, rather than * - 1. Create a new Entity Diagram under the Model Browser and add the tables you're investigating (and their related tables), and you'll be able to easily see (and change) the multiplicities.

XtraSimplicity
  • 5,704
  • 1
  • 28
  • 28