Search code examples
c#entity-framework-6db-first

EF Cannot remove object


In my model I have similar tables:

  • Persons (ID-NAME) e.g. (1-Paul - 2-Frank - 3-George)

  • Roles (ID-NAME) e.g. (1-Admin - 2-Developer - 3-Junior)

  • Persons_Roles (ID_PERSON Not Null - ID_ROLE Not Null e.g. (1-1 - 1-2 - 2-3 - 2-1 - 3-2)

Table Persons_Roles has a foreign key on both Persons and Roles tables.

I need to delete a role. I actually do

Persons oP = DbContext.Persons.Single(p=>p.ID == 1);
Persons_Roles oR = oP.Persons_Roles.Single(p=>p.ID_ROLE == 2);
oP.Persons_Roles.Remove(oR);
DbContext.SaveChanges();

But I get this error

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.

Why am I getting this error and what do I do to fix it?


Solution

  • If you want to delete a rule, you must first delete all the records that are refrenced to that rule. For example, you must first clear all the records in the Person_Roles table and then delete the rule from Role Table

    var personRoles = DbContext.Persons_Roles.Where(p=>p.ID_ROLE == 2).ToList();
    DbContext.Persons_Roles.RemoveRange(personRoles);
    var role = DbContect.Roles.Single(a=>a.ID==2);
    DbContext.Roles.Remove(role);
    DbContext.SaveChanges();