0

I have very simple models and I'd want to modify (remove) an element of
collection which is a property of one of them.

public class Student
{
   [Key]
   [Column(Order = 1)]
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string SecondName { get; set; }
   public int DepartamentID { get; set; }
}

public class Departament
{
   [Key]
   [Column(Order = 1)]
   public int Id { get; set; }
   public string Title { get; set; }
   public virtual ICollection<Student> Students { get; set; }
}

private void Remove(List<int> IDsOfStudentsToRemove)
{
    foreach (int id in IDsOfStudentsToRemove)
    {
       var Student = StudentContext.Students.Find(id);

       var Departament = DepartamentsContext
            .Departaments.Find(Student.DepartamentID);

       // That's what I'd want to achieve:
       // Remove student from Departament's Students collection
       // then remove student from Students Table

       Departament.Students.Remove(Student);
       StudentContext.Students.Remove(Student);
    }

    StudentContext.SaveChanges();
    DepartamentContext.SaveChanges();
}

But that's the error that I'm receiving

System.InvalidOperationException: '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.'

Very similar thread:

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

Thanks in advance

Xiaox
  • 15
  • 2
  • 1
    Why don't you simply delete the student (`StudentContext.Students.Remove(Student);`). If the cascade delete for the relationship is on, it will be automatically removed from department students. – Ivan Stoev Apr 03 '18 at 11:46
  • @IvanStoev Unfortunely, probably I did something bad during modeling or I simply didnt create relations (cuz Im trying to figure it out) and it doesnt work like that :[ – Xiaox Apr 03 '18 at 12:28

0 Answers0