Linq级联删除 CascadingDeleteOnSubmit

函数

用递归获取外键关联记录,从最外面一直删到最里面(本身)。

获取外键关联记录的办法是找有AssociationAttribute属性的Property,然后遍历,删除。

1 public static void CascadingDeleteOnSubmit(this DataContext context, object entity)
2 {
3 var entityType = entity.GetType();
4 var entityProperties = entityType.GetProperties();
5 //查找是否有“AssociationAttribute”标记的属性
6 //(Linq中有“AssociationAttribute”标记的属性代表外表)
7   var associationProperties = entityProperties.Where(
8 c => c.GetCustomAttributes(true).Any(
9 attrbute => attrbute.GetType().Name == "AssociationAttribute")
10 & c.PropertyType.IsGenericType);//该属性必需是泛型
11 //其他表有外键关联的记录
12   foreach (var associationProperty in associationProperties)
13 {
14 //获取Property值
15   object propertyValue = associationProperty.GetValue(entity, null);
16 //Property是EntitySet`1类型的值,如EntitySet<DataSetStructure>,
17 //而EntitySet`1有IEnumerable接口
18   IEnumerable enumerable = (IEnumerable)propertyValue;
19 foreach (object o in enumerable)
20 {
21 //递归
22   CascadingDeleteOnSubmit(context, o);
23 }
24 }
25
26 try
27 {
28 //删除没外键关联的记录
29 context.GetTable(entity.GetType()).DeleteOnSubmit(entity);
30 }
31 catch (Exception ex)
32 {
33 throw ex;
34 }
35 }

用法:

1 public virtual string CascadingDelete(string id)
2 {
3 TDataContext context = new TDataContext();
4 TEntity t = context.GetTable<TEntity>().Where(c => c.ID.Equals( id)).First();
5 context.CascadingDeleteOnSubmit(t);
6 context.SubmitChanges();
7 return Constances.ErrorMassage.SUCCEED;
8 }

posted on 2011-03-15 10:41  周伟光  阅读(924)  评论(0编辑  收藏  举报