Linq to SQL级联删除与反射

编程入门 行业动态 更新时间:2024-10-22 19:36:26
本文介绍了Linq to SQL级联删除与反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在寻找将linq中的级联删除从c#级联到sql的通用解决方案,但是我找不到任何解决方案.

I was looking for a general solution for cascading delete in linq to sql from c#, but I could not find any yet.

所以我想出了自己的解决方案,该解决方案处理一对多关系.

So I came up with my own solution, which handles one to many relations.

这不是删除实体的一般方法,但是某些情况下需要这样做.因此,在进入生产环境之前,我想知道您对此有何想法?

It would not be the general way to delete entities, but some edge case requires it. So before it goes to the production environment, I would like to know that what are you think about it?

这似乎可行,但是在哪里会失败,它的利弊是什么?请注意,它仅应遍历关系树的下方.

It seems to work, but what are the pros and cons, where it can fail? Note that it only supposed to traverse the relation tree downside.

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(); } } }

非常感谢您,

内格拉

推荐答案

解决方案的优点:

  • 很通用
  • 不需要在架构更新上更改数据库

缺点:

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

有一个不太复杂但需要大量维护的解决方案,它是将 ON CASCADE DELETE 规则添加到数据库中.

There is a less complex, but more maintenance heavy solution, which is adding ON CASCADE DELETE rules into your database.

更多推荐

Linq to SQL级联删除与反射

本文发布于:2023-10-16 05:43:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496667.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   级联   Linq   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!