2011-06-30 66 views
1

我一直在寻找的级联删除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(); 
      } 
     } 
    } 

非常感谢你,

荆您的解决方案

+0

如何beforeDeleteCallback使用? – Flater

+0

这是一个检查点,我们用它来记录被删除实体的细节。你也可以将这个过程从回调中分解出来(我们没有为它使用它,但是我是这样做的)。所以例如'helper.Delete(实体,O => {Console.WriteLine(○);返回true;});' –

回答

0

优点:

  • 它并不需要在架构更新数据库的变化这是通用

缺点:

  • 易错(多个自定义代码)
  • 性能是(很可能)不是最佳的

有一种较不复杂的,但更多的维护重溶液,将其加入ON CASCADE DELETE规则到您的数据库。

+0

可惜的是,ON CASCADE DELETE不是现在的选项。一个命令行维护系统将使用它(管理工具,手动启动,很少),主要业务应用程序(sp + sl + wcf)不会,所以我认为性能是可以接受的。你做? –