0

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?

Kit
  • 20,354
  • 4
  • 60
  • 103
Fudo
  • 3
  • 2

2 Answers2

1

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();
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
  • Hi, sorry i meant i want to delete a PERSON_ROLE not a role. The issue is in the first part of your code: DbContext.Persons_Roles.RemoveRange(personRoles); That's where i get the error. – Fudo Jul 12 '19 at 06:11
  • @Fudo No, that's exactly what you should do, not `oP.Persons_Roles.Remove(oR);`. When you remove from `oP.Persons_Roles` EF will try to set a FK to null, whereas removing from `DbContext.Persons_Roles` will delete the record. – Gert Arnold Jul 12 '19 at 10:02
  • I now see what you mean. Thanks not it's ok ! – Fudo Jul 12 '19 at 11:20
0

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