开发者

Linq to SQL cascading delete with reflection

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)
                    {
                        Associa开发者_如何学GotionAttribute 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();
            }
        }
    }

Thank you very much,

negra


Pros of your solution:

  • It's generic
  • It does not require database changes on schema updates

Cons:

  • Error prone (more custom code)
  • Performance is (most likely) not optimal

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜