Error:A referential integrity constraint violation occurred on db.SaveChanges() in .net?
.net, entity-framework, foreign-key-relationship, invalidoperationexception
Solution
You instantiate `phnumber` only once and then try to insert it in the database multiple times. Move the `PhoneNumber phnumber = new PhoneNumber();` phrase inside the `foreach (var ph in phoneList)` Block.
Problem
I have a created a WPF application with `Entity framework 4.0.` When i am trying to insert record in `PhoneNumber` Table it inserts first record successfully. But, when i loop through some List and try to insert another item into `PhoneNumber` table it Insert the record but shows error as: InvalidOperationException was handled by user code: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship. Code in .cs file: ``` protected void InsertContact(List<PhoneNumbersList> phoneList,otherparameters here) { Contact contact = new Contact(); PhoneNumber phnumber = new PhoneNumber(); //INSERT into Contacts Table contact.PrefixTitleID = cfnm.PrefixTitleID;// cfnm.Title; contact.FirstName = cfnm.FirstName; contact.MiddleName = cfnm.MiddleName; contact.LastName = cfnm.LastName; contact.Website = webpageaddress; contact.SuffixID = cfnm.SuffixID; contact.Gender = gender; contact.IMAddress = imaddress; db.Contacts.Add(contact); db.SaveChanges(); int contactid=contact.ContactID; if (contactid > 0) { int phid = 0; //INSERT into PhoneNumber Table foreach (var ph in phoneList) { phnumber.PhoneTypeID = ph.PhoneTypeID; phnumber.CountryID = ph.CountryID; phnumber.City = ph.City; phnumber.LocalNumber = ph.LocalNumber; phnumber.Extension = ph.Extension; phnumber.CountryCode = ph.CountryCode; db.PhoneNumbers.Add(phnumber); db.SaveChanges();//Getting Error here phid=phnumber.ID ; if(phid > 0) { //Save in ContactPhoneNumber Table contactphonenumber.ContactID = contactid; contactphonenumber.PhoneNumberID = phid; db.ContactPhoneNumbers.Add(contactphonenumber); db.SaveChanges(); } } } } ``` Getting Error after inserting Second record in `PhoneNumber` table. Any idea? Table Structure: Help Appreciated!