在Entity Framework中实现RemoveRange

时间:2017-03-17 08:09:27

标签: c# entity-framework-6

我正在尝试从数据库中删除记录范围并尝试以下方式:

 public void DeleteAllRolesFromUser(int userId, FilterDto filter)
        {
            var unitOfWork = _serviceLocator.Resolve<IUnitOfWork>();
            var filterValidatorService = _serviceLocator.Resolve<IFilterValidatorService>();

            // Prep filter if properties are null
            filter = filterValidatorService.ValidateListFilter(filter);           

            var userRoles = GetUserRoles(userId, filter);
            var usersAllRoles = new List<UserRole>();

            foreach (RoleDto role in userRoles)
            {
                var UserRole = new UserRole();
                UserRole.RoleId = role.Id;
                UserRole.UserId = userId;
                usersAllRoles.Add(UserRole);
            }
            // Delete user role
            unitOfWork.UserRoles.RemoveRange(usersAllRoles);

            // Perform changes
            unitOfWork.SaveChanges();
        }

UserRole和RoleDto的位置如下:

    public class UserRole : IdentityUserRole<int>, IModelWithId
        {
            public int Id {get; set; }

            public int UserId { get; set; }
            public virtual User User { get; set; }

            public int RoleId { get; set; }
            public virtual Role Role { get; set; }
        }
public class RoleDto : IModelWithId
    {
        public int Id { get; set; }    

        public string Name { get; set; }    

        public string Description { get; set; }

        public bool Active { get; set; }

        public bool CanExport { get; set; }

        public int? UserCount { get; set; }
    }

我收到错误:无法删除该对象,因为在ObjectStateManager中找不到该对象。

3 个答案:

答案 0 :(得分:0)

为什么不

unitOfWork.UserRoles.RemoveRange(unitOfWork.UserRoles.where(r=>r.UserId==userId));

您收到错误是因为您的新UserRole对象刚刚创建,您没有从dbcontext获取它们。所以他们需要以某种方式链接到您的dbcontext。附加功能就是这个原因。

尝试拨打

            foreach (RoleDto role in userRoles)
        {
            var UserRole = new UserRole();
            UserRole.RoleId = role.Id;
            UserRole.UserId = userId;
            usersAllRoles.Add(UserRole);
            unitOfWork.UserRoles.Attach(UserRole);
        }
        // Delete user role
        unitOfWork.UserRoles.RemoveRange(usersAllRoles);

答案 1 :(得分:0)

这意味着实体没有附加(它没有被相同的上下文加载)。 试试这个:

foreach (RoleDto role in userRoles)
            {
                var UserRole = new UserRole();
                UserRole.RoleId = role.Id;
                UserRole.UserId = userId;
                unitOfWork.UserRoles.Attach(UserRole);
                unitOfWork.Entry(UserRole).State = EntityState.Deleted;
            }
            unitOfWork.SaveChanges();

答案 2 :(得分:0)

我做了另一种方式。我在列表中使用userId获取了所有记录,然后使用RemoveRange()运行良好而没有错误。

in:MY.C_UTI_MAJ:6:compared to:6
in:MY.C_UTI_CRE:6:compared to:6
in:MY.C_TYP_PARAM:20:compared to:20
in:MY.PARAM:16:compared to:20
in:MY.DESCRIPTION:245:compared to:255