将多实体框架更新为多实体框架.无法从多表到多表中删除

本文关键字:框架 实体 删除 更新 | 更新日期: 2023-09-27 17:57:15

用户和角色之间存在多对多关系。我可以轻松地将角色添加到多对多表中,但我无法删除它,它不会给我任何错误,但不会删除要删除的角色。我尝试了我发现的一切。这是我的代码。

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;
        }
    }

我错过了什么?

将多实体框架更新为多实体框架.无法从多表到多表中删除

若要从实体中删除实体,必须先在实体中加载此实体。

尝试使用

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();