我試圖從數據庫中刪除記錄的範圍,並嘗試如下方法:實體框架中實現RemoveRange
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中找不到。
UserRoles是一個存儲庫,它沒有Where方法。 – Dipak