I am attempting to delete a series of entities using EntityFramework 4. Here is the code I am using:
var role = (
from r in context.tblAdminRoles
where r.AdminRoleId == this.Role.AdminRoleId
select r
).First();
this.AdminUser.tblAdminRoles.Remove(role);
context.SaveChanges();
context.tblAdminRoles.Remove(role);
context.SaveChanges();
However, when I execute it, I get the following error:
The DELETE statement conflicted with the REFERENCE constraint
"FK_tblAdminUserRole_tblAdminRole". The conflict occurred in database"MyMainSite2", table"dbo.tblAdminUserRole", column'AdminRoleId'.The statement has been terminated.
My database has the following structure:
---------------- -------------------- ----------------
| | | | | |
| tblAdminUser | ---< | tblAdminUserRole | >--- | tblAdminRole |
| | | | | |
---------------- -------------------- ----------------
Can anyone point me in the right direction about what might be going wrong?
Check if cascading delete is enabled in the database for the two relationships refering to the link table
tblAdminUserRole, especially for theFK_tblAdminUserRole_tblAdminRoleto thetblAdminRoletable. It looks like it isn’t enabled, therefore deleting the role doesn’t delete the entries in the link table which finally leads to the FK constraint violation.