Reputation: 57469
How do I delete all child objects in in a many to many scenario? For example, I'd like to delete all roles
belonging to a user
.
I'm using EF code first.
Upvotes: 2
Views: 5134
Reputation: 1785
In the SaveChanges of my DbContext
var trackPublication = ChangeTracker.Entries<Publication>();
var dbEntityEntriesPublication = trackPublication as IList<DbEntityEntry<Publication>> ?? trackPublication.ToList();
foreach (var item in dbEntityEntriesPublication.Where(t => t.State == EntityState.Deleted))
{
item.State = EntityState.Unchanged;
item.Collection(m=>m.Groups).Load();
item.Entity.Groups.Clear();
item.State = EntityState.Deleted;
}
Upvotes: 0
Reputation: 5933
The key is to convert the set of entities to delete into a list so you can iterate and affect them.
var usersRoles = user.Roles.ToList();
foreach (var role in usersRoles )
Context.DeleteObject(role );
Upvotes: 0
Reputation: 6050
For many to many relationships the default in EF Code First is cascade delete if you're letting EF create the database. So if you delete the User the roles should go away automatically. If you have an existing database and can set it up for cascade delete that would probably still be the simplest and most efficient solution.
Upvotes: 1
Reputation: 364249
Do you really want to delete roles belonging to user? It means that roles records will be deleted which will most probably result in exception because in many-to-many scenario roles will be usde by other users.
If you setup everything correctly this should simply remove relations between user and his roles:
var user = context.Users.Include("Roles").Single(u => u.Id == id);
user.Roles.Clear();
context.SaveChanges();
Upvotes: 7
Reputation: 6743
First you must select all the roles and remove then from the user instance roles collection. Save
var usersRoles = user.Roles.ToList();
usersRoles.ForEach(role => user.Roles.Remove(role));
context.SaveChanges();
// Add new roles to the user
PS. the code may not be exact, but this is the logic that you should use to acomplish this.
Upvotes: 5