c# - Update Many to Many Entity Framework. Cannot remove from many to many table -
there many many relationship between user , roles. can add role many many table, cannot remove it, not give me error don't remove roles remove. try found. here code.
public user update(user entity) { using (var context = new enersysentities()) { var user = context.users.single(u => u.user_id == entity.user_id); //all roles in data base list<role> rolealreadyassigned = getbyid(entity.user_id).roles.tolist(); //roles remove list<role> rolestoremove = rolealreadyassigned.where(x => entity.roles.all(y => y.role_id != x.role_id)).tolist(); //roles add list<role> rolestoadd = entity.roles.where(x => rolealreadyassigned.all(y => y.role_id != x.role_id)).tolist(); foreach (role roletodelete in rolestoremove.tolist()) { // remove roles rolestoremove user.roles.remove(roletodelete); } //add roles not in list of rolestoadd foreach (role rol in rolestoadd) { var newrole = new role { role_id = rol.role_id }; context.roles.attach(newrole); user.roles.add(newrole); } context.savechanges(); return entity; } }
what i'm missing?
to remove entities entity it's necessary entities loaded before in entity.
try with
var user = context.users.include(u => u.roles).where(u => u.user_id == entity.user_id).firstordefault; list<role> rolestoremove = user.roles.where(x => entity.roles.all(y => y.role_id != x.role_id)).tolist(); //roles add list<role> rolestoadd = entity.roles.where(x => user.roles.all(y => y.role_id != x.role_id)).tolist();
Comments
Post a Comment