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:
Thanks in advance