EF codefirst delete all child objects in a many-many scenario?
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 开发者_StackOverflow社区user
.
I'm using EF code first.
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();
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.
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.
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 );
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;
}
精彩评论