Implement RemoveRange in Entity Framework

c# entity-framework-6

Question

I am trying to delete range of record from database and trying as following way:

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

Where UserRole and RoleDto is like:

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

I am getting error : The object cannot be deleted because it was not found in the ObjectStateManager.

1
0
3/17/2017 8:09:27 AM

Accepted Answer

I did it another way. I got all the records using userId in a list and then using RemoveRange() worked well without error.

 var userRoles = unitOfWork.UserRoles.GetByUserId(userId).ToList();
            // Delete user role
            unitOfWork.UserRoles.RemoveRange(userRoles);

            // Perform changes
            unitOfWork.SaveChanges();
0
3/17/2017 9:17:01 AM

Popular Answer

It means that entity isn't attached (it wasn't loaded by the same context). Try this:

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow