You can make the second exception disappear by attaching the role
to the context first before you call Remove
:
_dataContext.Roles.Attach(role);
_dataContext.Roles.Remove(role);
_dataContext.SaveChanges();
But then you will most likely get the first exception also for this code because the real problem is that you apparently don't have enabled cascading delete in the database for the two relationships from UserRoles
table to Users
table and Roles
table respectively.
You can set the Delete Rule for both relationships to "Cascade" in SQL Server Management Studio like show here for example. After that deleting a role should also delete the entries in the UserRoles
link table.
Edit
When you load the related users you can also delete a role successfully without having cascading delete enabled:
var role = _dataContext.Roles.Include(r => r.Users)
.Single(r => r.Id == someRoleId);
_dataContext.Roles.Remove(role);
// _dataContext.Entry(role).State = EntityState.Deleted; will work as well
_dataContext.SaveChanges();
The difference is that when the related users are attached to the context together with the role EF will send a separate DELETE statement for each row in the UserRoles
link table and then a DELETE statement for the role so that it works without violating a FK constraint.