Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing object mapping many to many relation in Entity Framework

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)?

like image 239
Kamil Będkowski Avatar asked Oct 08 '22 04:10

Kamil Będkowski


1 Answers

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.

like image 66
Damir Arh Avatar answered Oct 12 '22 10:10

Damir Arh