[英]EF 6.1.1 - The relationship could not be changed because one or more of the foreign-key properties is non-nullable
I am getting this error when trying to remove relations between entities and creating new ones. 尝试删除实体之间的关系并创建新实体时,出现此错误。
public partial class Course
{
public int Course_ID { get; set; }
/* CODE*/
public virtual ICollection<Student> Students { get; set; }
}
public partial class Student
{
public int Student_ID { get; set; }
/* CODE*/
public virtual ICollection<Course> Courses { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
public partial class Book
{
public int Book_ID { get; set; }
public int Student_ID { get; set; }
/* CODE*/
public virtual Student Student { get; set; }
}
The relations is as follows: 关系如下:
I'm trying to update a Student Entity like this: 我正在尝试像这样更新学生实体:
public bool UpdateEntity(Entities.Student student)
{
using (var context = new Entities())
{
var record = context.Students
.Include("Courses")
.Include("Books")
.FirstOrDefault(c => c.Student_ID == student.Student_ID );
// record.Courses.ToList().ForEach(s => record.Courses.Remove(s));
// record.Books.ToList().ForEach(t => record.Books.Remove(t));
record.Courses.Clear();
record.Books.Clear();
record.Courses= student.Courses;
record.Books= student.Books;
context.SaveChanges();
return true;
}
}
A relation between a student and a course should be removed without removing the actual course. 学生和课程之间的关系应该删除而不删除实际课程。 When updating a relation between a book and a student, the book should be deleted as well.
更新书本与学生之间的关系时,也应删除该书。
EDIT updated to make it clearer 编辑已更新,使其更清晰
When you want to remove items in a 1-many collection from the database you have to mark each item for delete, eg like so: 当您要从数据库中删除多个集合中的项目时,必须将每个项目标记为删除,例如:
foreach (var book in record.Books)
{
context.Books.Remove(book);
}
context.SaveChanges();
It's a nuisance sometimes. 有时候很麻烦。 When you
Clear
a collection navigation property, EF errs on the side of caution and tries to only break the association without deleting the items, ie its tries to nullify the foreign keys. 当您
Clear
集合导航属性时,EF谨慎行事,并尝试仅中断关联而不删除项目,即,其尝试使外键无效。 However, EF does know that the FK field is not nullable in the database, so it seems to me that EF should be able to figure out that in this case it's the user's intention to delete items, rather than to orphan them. 但是,EF 确实知道 FK字段在数据库中不能为空,因此在我看来,EF 应该能够弄清楚在这种情况下,用户的目的是删除项目而不是孤立项目。 But too bad, it doesn't.
但是太糟糕了,事实并非如此。
I used to work with NHibernate and IIRC, NHibernate did delete child items in similar cases, even firing a one-shot delete ( delete from Child where Child.ParentId = ...
). 我曾经与NHibernate和IIRC一起工作过,NHibernate确实在类似情况下删除了子项,甚至触发了一次删除操作(
delete from Child where Child.ParentId = ...
)。 EF fires a delete statement for each child separately. EF分别为每个孩子触发一个delete语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.