你可以找到源代码演示这个问题@http://code.google.com/p/contactsctp5/CTP5 EF代码优先问题
我有三个模型对象。联系,的ContactInfo,ContactInfoType。如果联系人有多个contactinfo,并且每个contactinfo都是contactinfotype。很简单,我猜。我遇到的问题是当我去编辑联系人对象时。我从我的联系人存储库中取出它。然后我运行“UpdateModel(contact);”并用我的表单中的所有值更新对象。 (与调试监控)当我保存更改,虽然,我得到以下错误:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
好像在我称之为更新模型,可以空值了我的引用,这似乎打破一切吗?任何想法如何补救将不胜感激。谢谢。
这里是我的模型:
public partial class Contact {
public Contact() {
this.ContactInformation = new HashSet<ContactInformation>();
}
public int ContactId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<ContactInformation> ContactInformation { get; set; }
}
public partial class ContactInformation {
public int ContactInformationId { get; set; }
public int ContactId { get; set; }
public int ContactInfoTypeId { get; set; }
public string Information { get; set; }
public virtual Contact Contact { get; set; }
public virtual ContactInfoType ContactInfoType { get; set; }
}
public partial class ContactInfoType {
public ContactInfoType() {
this.ContactInformation = new HashSet<ContactInformation>();
}
public int ContactInfoTypeId { get; set; }
public string Type { get; set; }
public virtual ICollection<ContactInformation> ContactInformation { get; set; }
}
我的控制器操作:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Contact person) {
if (this.ModelState.IsValid) {
var contact = this.contactRepository.GetById(person.ContactId);
UpdateModel(contact);
this.contactRepository.Save();
TempData["message"] = "Contact Saved.";
return PartialView("Details", contact);
} else {
return PartialView(person);
}
}
上下文代码:
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {
modelBuilder.Entity<Contact>()
.HasMany(c => c.ContactInformation)
.WithRequired()
.HasForeignKey(c => c.ContactId);
modelBuilder.Entity<ContactInfoType>()
.HasMany(c => c.ContactInformation)
.WithRequired()
.HasForeignKey(c => c.ContactInfoTypeId);
}
错误与您在表单上进行的更改类型无关吗?我可以想象,如果您从Contact中的集合中删除“ContactInformation”,就会发生这样的错误。如果你只改变表单上的'FirstName'而没有其他的事情发生,错误也会发生吗? – Slauma 2011-03-06 15:48:19