错误:参照完整性约束冲突发生在db.SaveChanges()在.net中? [英] Error:A referential integrity constraint violation occurred on db.SaveChanges() in .net?
问题描述
我有一个创建一个WPF应用程序实体框架4.0。
当我试图插入记录在联系号码
表它插入第一个记录成功。但是,当我遍历了一些列表,并尝试插入另一个项目插入联系号码
表它插入记录,但显示的错误为:
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异常是由用户code处理: 该数据库的更改被成功地提交,但在更新对象上下文时发生错误。 ObjectContext中可能会处于不一致的状态。内蒙古异常消息:参照完整性约束冲突发生:定义参照约束的属性值是不是本金和依赖对象的关系之间是一致的的
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在cs文件:
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:
帮助鸭preciated!
Help Appreciated!
推荐答案
您实例 phnumber
只有一次,然后尝试将其插入到数据库中多次。移动联系号码phnumber =新的联系号码();
短语里面的foreach(在PHONELIST VAR PH)
块。
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.
这篇关于错误:参照完整性约束冲突发生在db.SaveChanges()在.net中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!