我正在寻找一个通用的解决方案,用于将linq中的级联删除从c#中删除到sql,但我还没找到。
所以我提出了自己的解决方案,它可以处理一对多关系。
这不是删除实体的一般方法,但有些边缘情况需要它。所以在进入生产环境之前,我想知道您对此有何看法?
它似乎有效,但有哪些优点和缺点,它可能会失败?请注意,它只应该遍历关系树的缺点。
public class CascadingDeleteHelper
{
public void Delete(object entity, Func<object, bool> beforeDeleteCallback)
{
if (!(entity is BusinessEntity))
{
throw new ArgumentException("Argument is not a valid BusinessEntity");
}
if (beforeDeleteCallback == null || beforeDeleteCallback(entity))
{
Type currentType = entity.GetType();
foreach (var property in currentType.GetProperties())
{
var attribute = property
.GetCustomAttributes(true)
.Where(a => a is AssociationAttribute)
.FirstOrDefault();
if (attribute != null)
{
AssociationAttribute assoc = attribute as AssociationAttribute;
if (!assoc.IsForeignKey)
{
var propertyValue = property.GetValue(entity, null);
if (propertyValue != null && propertyValue is IEnumerable)
{
IEnumerable relations = propertyValue as IEnumerable;
List<object> relatedEntities = new List<object>();
foreach (var relation in relations)
{
relatedEntities.Add(relation);
}
relatedEntities.ForEach(e => Delete(e, beforeDeleteCallback));
}
}
}
}
SingletonDataContext.DataContext.GetTable(currentType).DeleteOnSubmit(entity);
SingletonDataContext.DataContext.SubmitChanges();
}
}
}
非常感谢,
内格拉
答案 0 :(得分:0)
您解决方案的优点:
缺点:
有一个不那么复杂但更加维护的解决方案,即在您的数据库中添加ON CASCADE DELETE
规则。