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?

2 answers

  • answered 2019-07-11 03:24 EsH Harshana

    You can not delete data if which is referenced to another table as foreign key, but you done through

    Remove value from referenced table after then you can able to perform delete operation only

  • answered 2019-07-11 04:21 Farhad Zamani

    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();