我不知道我真的遇到了这个问题,我无法得到解决方案。
我有此代码来更新我的联系人和联系人组。
var originalContact = GetContact(contactToEdit.Id);
// Update with new group
originalContact.groups = GetGroup(groupId);// Exception : A referential integrity constraint violation occurred: A property that is a part of referential integrity constraint cannot be changed when the object has a non-temporary key.
// Save changes
_entities.ApplyPropertyChanges(originalContact.EntityKey.EntitySetName, contactToEdit);
_entities.SaveChanges();
return contactToEdit;
每当我更新联系人时,正常的字段,即姓名,电子邮件和联系人都可以正常工作...... 但是当我尝试更新关系时,即它带有此异常的组
异常:发生参照完整性约束违规:当对象具有非临时密钥时,无法更改作为参照完整性约束一部分的属性。
我尝试了很多解决方案,但有时候无法解决这个问题,有时它会使用更新后的群组创建新条目......
我完全迷失了,请有人帮忙。
[更新]
你好Alex, 我有一个服务类名称ContactManagerService
public class ContactManagerService : IContactManagerService
{
private IValidationDictionary _validationDictionary;
private IContactManagerRepository _repository;
public ContactManagerService(IValidationDictionary validationDictionary)
: this(validationDictionary, new EntityContactManagerRepository())
{ }
public ContactManagerService(IValidationDictionary validationDictionary, IContactManagerRepository repository)
{
_validationDictionary = validationDictionary;
_repository = repository;
}
public bool ValidateContact(Contact contactToValidate)
{
if (contactToValidate.FirstName.Trim().Length == 0)
_validationDictionary.AddError("FirstName", "First name is required.");
if (contactToValidate.LastName.Trim().Length == 0)
_validationDictionary.AddError("LastName", "Last name is required.");
if (contactToValidate.Phone.Length > 0 && !Regex.IsMatch(contactToValidate.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
_validationDictionary.AddError("Phone", "Invalid phone number.");
if (contactToValidate.Email.Length > 0 && !Regex.IsMatch(contactToValidate.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
_validationDictionary.AddError("Email", "Invalid email address.");
return _validationDictionary.IsValid;
}
public bool EditContact(int id, Contact contactToEdit)
{
// Validation logic
if (!ValidateContact(contactToEdit))
return false;
// Database logic
try
{
_repository.EditContact(id,contactToEdit);
}
catch
{
return false;
}
return true;
}
}
这是对EntityContactRepository类进行EditContact调用
public class EntityContactManagerRepository : ContactManager.Models.IContactManagerRepository
{
private ContactManagerDBEntities _entities = new ContactManagerDBEntities();
//public Contact GetContact(int id)
//{
// return (from c in _entities.ContactSet
// where c.Id == id
// select c).FirstOrDefault();
//}
public IEnumerable<Contact> ListContacts()
{
return _entities.ContactSet.ToList();
}
public Contact GetContact(int id)
{
return (from c in _entities.ContactSet.Include("groups")
where c.Id == id
select c).FirstOrDefault();
}
public Group GetGroup(int id)
{
try
{
return (from g in _entities.GroupSet //.Include("contacts")
where g.Id == id
select g).FirstOrDefault();
}
catch
{
return new Group();
}
}
public Contact EditContact(int groupId, Contact contactToEdit)
{
var originalContact = GetContact(contactToEdit.Id);
// Update with new group
originalContact.groups = GetGroup(groupId);// Exception : A referential integrity constraint violation occurred: A property that is a part of referential integrity constraint cannot be changed when the object has a non-temporary key.
// Save changes
_entities.ApplyPropertyChanges(originalContact.EntityKey.EntitySetName, contactToEdit);
_entities.SaveChanges();
return contactToEdit;
}
}
这是来自mvc网站的教程...... http://www.asp.net/learn/mvc/tutorial-31-cs.aspx
&lt; [Update 2]&gt;
这是我的ContactController代码
public ActionResult Edit(int id)
{
//var contactToEdit = (from c in _entities.ContactSet
// where c.Id == id
// select c).FirstOrDefault();
//return View(_repository.GetContact(id)); //; contactToEdit);
//return View(_service.GetContact(id));
var contactToEdit = _service.GetContact(id);
AddGroupsToViewData((int) (contactToEdit.groups.Id));
return View("Edit", contactToEdit);
}
//
// POST: /Home/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int groupId, Contact contactToEdit)
{
if (_service.EditContact(groupId, contactToEdit))
return RedirectToAction("Index", new { id = groupId });
AddGroupsToViewData(groupId);
return View("Edit");
}
[解决方案]
您好我在数据库结构上犯了一个愚蠢的错误,最初就像是
DROP TABLE IF EXISTS `contentmanagement`.`groups`;
CREATE TABLE `contentmanagement`.`groups` (
`Id` int(11) NOT NULL auto_increment,
`Name` varchar(45) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `contentmanagement`.`contacts`;
CREATE TABLE `contentmanagement`.`contacts` (
`Id` int(11) NOT NULL auto_increment,
`FirstName` varchar(50) character set utf8 collate utf8_unicode_ci NOT NULL,
`LastName` varchar(50) character set utf8 collate utf8_unicode_ci NOT NULL,
`Phone` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`GroupId` int(11) NOT NULL,
PRIMARY KEY USING BTREE (`Id`,'GroupId'),
KEY `FK_contacts_1` (`GroupId`),
CONSTRAINT `FK_contacts_1` FOREIGN KEY (`GroupId`) REFERENCES `groups` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我将其更新为
DROP TABLE IF EXISTS `contentmanagement`.`groups`;
CREATE TABLE `contentmanagement`.`groups` (
`Id` int(11) NOT NULL auto_increment,
`Name` varchar(45) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `contentmanagement`.`contacts`;
CREATE TABLE `contentmanagement`.`contacts` (
`Id` int(11) NOT NULL auto_increment,
`FirstName` varchar(50) character set utf8 collate utf8_unicode_ci NOT NULL,
`LastName` varchar(50) character set utf8 collate utf8_unicode_ci NOT NULL,
`Phone` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`GroupId` int(11) NOT NULL,
<b> PRIMARY KEY USING BTREE (`Id`),
Index(`GroupId`),</b>
KEY `FK_contacts_1` (`GroupId`),
CONSTRAINT `FK_contacts_1` FOREIGN KEY (`GroupId`) REFERENCES `groups` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
它解决了我的问题 谢谢......