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

Upvotes: 0

Views: 64

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109080

When you want to remove items in a 1-many collection from the database you have to mark each item for delete, e.g. 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, i.e. its tries to nullify the foreign keys. 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. 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 = ...). EF fires a delete statement for each child separately.

Upvotes: 1

Related Questions