C# – DbUpdateException on SaveChanges if child foreign key already exists – in Entity Framework Code First

centity-frameworknetormsql

[ Using Code First DbContext with Entity Framework 5.0 RC ]

Entity with 2 Navigational Properties / 2 Foreign Keys

public class Compositon
{

    public string Id { get; set; }

    public string SimpletonId { get; set; }

    [ForeignKey("SimpletonId")]
    public Simpleton Simpleton { get; set; }

    public string CompanitonId { get; set; }

    [ForeignKey("CompanitonId")]
    public Companiton Companiton { get; set; }
}

First Pass – SaveChanges to Empty Database Works

var composition = new Compositon();
compositon.Id = "UniquePrimaryKey";
var simpleton = new Simpleton();
// This foreign key does not exist in database yet
simpleton.Id = "Simpleton1";
composition.Simpleton = simpleton;
var companiton = new Companiton();
companiton.Id = "SomeOther1";
composition.Companiton = companiton;
// Repositor references the DbContext
Repositor.Compositons.Add(composition);
Repositor.SaveChanges();

Second Pass – Existing Child Foreign Key Leads to Parent Fault

var composition = new Compositon();
compositon.Id = "AnotherUniquePrimaryKey";
var simpleton = new Simpleton();
// This foreign key already exists in database
simpleton.Id = "Simpleton1";
composition.Simpleton = simpleton;
var companiton = new Companiton();
companiton.Id = "SomeOther2";
composition.Companiton = companiton;
Repositor.Compositons.Add(composition);
Repositor.SaveChanges();

DbUpdateException: An error occurred while updating the entries.

I need to be able save these parent classes into the database, because they are unique even though they sometimes contain a navigational property that is already stored – how can I save the parent from this child primary key conflict?

Best Answer

In the second pass you will need to retrieve the existing Simpleton from the DbContext. I'm guessing that you could do that like this:

`simpleton = Repositor.Simpletons.First(s => s.Id == "Simpleton1");`

Currently, you're creating a brand new one, which the Entity Framework tries to insert as such, hence the key violation.