Removing object mapping many to many relation in Entity Framework

c#, entity-framework

Solution

You need to remove all the roles from the user object before calling `SaveChanges()` on the context:

var aspnetUser = _db.aspnet_Users.Single(a => a.UserId == id);

foreach(var role in aspnetUser.Roles.ToArray())
{
    aspnetUser.Roles.Remove(role);
}

_db.aspnet_Users.DeleteObject(aspnetUser);

_db.SaveChanges();

This will prevent the exception caused by the referential constraints in the database and ensure that the corresponding records in UsersInRoles table get deleted.

Problem

In ASP.NET MVC I have three tables: `Users`, `Roles`, `UsersInRoles` (standard many to many joining table). When I've mapped it to EF, it created two Entity Types: `Users` and `Roles`. Now I want to delete some user using code like below: ``` var aspnetUsers = _db.aspnet_Users.Single(a => a.UserId == id); _db.aspnet_Users.DeleteObject(aspnetUsers); ``` of course I can't do it, because in SQL level in table `UsersInRoles` there is a connected row. How to delete that row from EF level (`UsersInRoles` table is not mapped)?

Original source