Friday, November 13, 2009

Cannot add an entity with a key that is already in use.

I got this error today while working with Linq2Sql.

I had an object "Person".

Person person = new Person();

Person has a property called Child, but the child already exists in the database. I thought that assigning the current child in the DB to the person.Child property would just set the value for the Person and not mess with child. It doesn't quite work that way.


person.Child = dc.Childs.Where(c => c.ChildID == childID).SingleOrDefault();


dc.Persons.InsertOnSubmit(person);
dc.SubmitChanges();


The last line will fail with the aformentioned error. I ended up using the ChildID property instead (the former was the better way for the problem at hand, but setting the child ID worked after adding some additional code) so it looked like this.


person.ChildID = childID;

dc.Persons.InsertOnSubmit(person);
dc.SubmitChanges();


The reason this happens is because  you are trying to save an object that is already in the database.
Nifty.