1
算目前我使用此代码:通用的方法在实体框架
opportunity.Contacts.Where(x => x.IsDeleted = false).IsNullOrEmpty()
在每个实体检查,如果在实体(例如Opportunity
)存在任何集合。
public bool Delete(int companyId, int opportunityId)
{
var opportunity = _opportunityRepository.FindOne(companyId: companyId, opportunityId: opportunityId).FirstOrDefault();
if (!opportunity.Contacts.Where(x => x.IsDeleted = false).IsNullOrEmpty())
{
throw new UserFriendlyException(ErrorMessages.UserFriendly.UnableToDeleteEntityHasRelatedData);
}
opportunity.IsDeleted = true;
_opportunityRepository.Edit(opportunity);
CurrentUnitOfWork.Commit();
return true;
}
这种方法是重复的,耗时数百个地方。
我们如何使它成为一个通用的功能,可以检查实体类型和使用反射或另一种方式来检查其所有特性,这实现ICollection<T>
和执行查询,以检查他们的计数?
[ForeignKey("DepartmentId")]
public virtual ICollection<DepartmentLocation> DepartmentLocations { get; set; }
[ForeignKey("DepartmentId")]
public virtual ICollection<EmployeePosition> EmployeePositions { get; set; }
为什么不启用级联删除的关系? – haim770
或者如果不需要级联,则禁用级联...删除级联的默认级别取决于所需的关系或可选... – grek40