EF 无法删除对象

EF Cannot remove object

在我的模型中有类似的表格:

Table Persons_RolesPersonsRoles 表上都有一个外键。

我需要删除一个角色。我真的

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

但是我得到这个错误

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.

为什么会出现此错误,我该如何解决?

如果引用另一个 table 作为外键,则不能删除数据,但您已通过

完成

从引用中删除值 table 之后您只能执行删除操作

如果要删除规则,必须先删除所有引用该规则的记录。 例如,必须先清除Person_Rolestable中的所有记录,然后删除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();