你可以找到源代碼演示這個問題@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