C#实体框架6 - 如何从DbSet.RemoveRange方法获取计数

时间:2016-03-22 20:34:57

标签: c# entity-framework

如何从DbSet.RemoveRange方法获取计数?当我尝试使用Count()时,它会在保存更改时抛出错误

_dbFileManagementRepository.FileManagements.RemoveRange(_dbFileManagementRepository.FileManagements.Where(x => x.Id == serviceId && x.DateAdded < purgeDate)).Count();
_dbFileManagementRepository.SaveChanges();

当我像这样分配它时,在保存更改时不会删除任何内容

var records = _dbFileManagementRepository.FileManagements.RemoveRange(_dbFileManagementRepository.FileManagements.Where(x => x.Id == serviceId && x.DateAdded < purgeDate));
int purgeCount = records.Count();
_dbFileManagementRepository.SaveChanges();

当我运行它时,它删除就好了:

_dbFileManagementRepository.FileManagements.RemoveRange(_dbFileManagementRepository.FileManagements.Where(x => x.Id == serviceId && x.DateAdded < purgeDate));
_dbFileManagementRepository.SaveChanges();

1 个答案:

答案 0 :(得分:2)

使用RemoveRange无论你做什么都需要两个查询,所以这应该适用于你的情况:

var toBeRemoved = _dbFileManagementRepository.FileManagements.Where(x => x.Id == serviceId && x.DateAdded < purgeDate).ToList();
var removedCount = toBeRemoved.Count;
_dbFileManagementRepository.FileManagements.RemoveRange(toBeRemoved);
_dbFileManagementRepository.SaveChanges();