![](/img/trans.png)
[英]Entity Framework 5 The relationship could not be changed because one or more of the foreign-key properties is non-nullable
[英]Trying to update record in entity framework The relationship could not be changed because one or more of the foreign-key properties is non-nullable
我整天都在搜尋,試圖找到解決問題的方法。 仍然沒有找到解決方案。
嘗試使用實體框架更新數據庫中的記錄時遇到此錯誤。
由於一個或多個外鍵屬性不可為空,因此無法更改該關系。 對關系進行更改時,相關的外鍵屬性將設置為空值。 如果外鍵不支持空值,則必須定義新的關系,必須為外鍵屬性分配另一個非空值,或者必須刪除不相關的對象。
public bool PostChangesStudent(Student updatedStudent)
{
// Get current student from the database.
var student = _db.Students.Find(updatedStudent.Id);
if (student != null)
{
// Clear all cources from the ICollection list.
student.Courses.Clear();
foreach (var course in updatedStudent.Courses)
{
// Adds the new edited courses
student.Courses.Add(course);
}
// Save changes in database
_db.Entry(student).State = EntityState.Modified;
_db.SaveChanges();
}
如錯誤所述,我刪除了“課程”列表中的舊課程對象,然后我猜應該添加新的關系嗎? 我只是不知道下一步該怎么做。
您所看到的是,我從數據庫(學生)獲得了(未編輯的)對象,並且可以使用參數(updatedStudent)檢索了updatedStudent對象。
學生和課程模型
public class Student
{
public int Id { get; set; }
public string StudentNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// Courses
public virtual ICollection<Course> Courses{ get; set; }
}
public class Course
{
public int Id { get; set; }
public int StudentId { get; set; }
public string CourseName { get; set; }
public int CourseNumber { get; set; }
}
這是一對多的關系,
我已經使用Context類和ContextInitializer設置了測試數據,使用本教程解決了這些問題:
已經讀過很多關於這個問題的文章,但是不知道該怎么辦。
更新
抱歉,我打錯了。.我很清楚地從數據庫中獲取的原始學生對象中提取課程。
然后,我遍歷了updatedStudent.Courses,它由編輯過的課程組成,並將它們映射到student對象中。
完成后,我想再次將對象保存在數據庫中,使其具有新的課程(更新的課程)。
UPDATE2
與danludwig討論之后,我終於使它起作用了:D
這是做什么的:
從學生對象清除課程,例如以下代碼:
foreach (var course in student.Courses.ToArray()) { _db.Entry(course).State = EntityState.Deleted; student.Courses.Remove(course); }
通過updatedStudent.Courses循環並將課程對象添加到學生對象。
foreach (var course in updatedStudent.Courses) { student.Courses.add(course); }
希望這可以幫助其他人解決這個瘋狂的錯誤!
我認為問題可能出在此行:
student.Courses.Clear();
...因為Course
具有2個不可為空的外鍵屬性。 當您從Student
清除這些內容時,您正在“改變關系”,因此EF將嘗試將Course.StudentId
設置為null。 不能。 因為它是一個不可為空的外鍵屬性。
您真的要刪除這些課程嗎? 如果是這樣,請刪除它們而不是將它們從集合中刪除(或在上下文中將其狀態標記為已刪除)。
// student.Courses.Clear(); get rid of this line, it is bad for you
foreach (var course in student.Courses.ToArray())
{
_db.Entry(course).State = EntityState.Deleted;
student.Courses.Remove(course);
}
如錯誤所述,我刪除了“課程”列表中的舊課程對象。
不,您不會在任何地方刪除任何內容。 在EF中,從一對多集合屬性中刪除項目與刪除項目不同 。 即使您從student.Courses
集合中刪除了它們,EF上下文仍在跟蹤這些實體,默認情況下,它們只會嘗試將其外鍵值設置為null。 不能。 因為它是一個不可為空的外鍵屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.