简体   繁体   中英

Update Many to Many Entity Framework. Cannot remove from many to many table

There is a many to many relationship between User and Roles. I can easily add the Role to the many to many table, but I cannot remove it, it does not give me any error but don't remove the roles to remove. I try everything I found. Here is my 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 the data base
            List<Role> roleAlreadyAssigned = GetById(entity.USER_ID).Roles.ToList();

            //Roles to remove
            List<Role> rolesToRemove =
                roleAlreadyAssigned.Where(x => entity.Roles.All(y => y.ROLE_ID != x.ROLE_ID)).ToList();

            //Roles to 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 the roles from rolesToRemove
                user.Roles.Remove(roleToDelete);

            }

            //Add the roles which are not in the 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 from Entity it's necessary that this entities were loaded before in your 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 to add
List<Role> rolesToAdd =
    entity.Roles.Where(x => user.Roles.All(y => y.ROLE_ID != x.ROLE_ID)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM