我一直在寻找的级联删除LINQ从C#到SQL中的通用的解决方案,但我无法找到任何呢。LINQ到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();
}
}
}
非常感谢你,
荆您的解决方案
如何beforeDeleteCallback使用? – Flater
这是一个检查点,我们用它来记录被删除实体的细节。你也可以将这个过程从回调中分解出来(我们没有为它使用它,但是我是这样做的)。所以例如'helper.Delete(实体,O => {Console.WriteLine(○);返回true;});' –