Пример #1
0
        public void DeleteHolder(string moniker)
        {
            using (var context = new BaseInfoDbContext(_connectionString))
            {
                var holderToRemove = GetHolder(moniker);

                if (holderToRemove != null)
                {
                    context.Remove(holderToRemove);
                    context.Holders.Remove(holderToRemove);
                    context.SaveChanges();
                }
            }
        }
Пример #2
0
        public static void CheckForRemove(this IEntity source, IEntity target, BaseInfoDbContext context)
        {
            foreach (var prop in source.GetType().GetProperties())
            {
                if (typeof(IEnumerable <IEntity>).IsAssignableFrom(prop.PropertyType))
                {
                    var targetProp = target.GetType().GetProperty(prop.Name);
                    if (targetProp == null)
                    {
                        continue;
                    }
                    var sourceValue = (IEnumerable <IEntity>)prop.GetValue(source);
                    var targetValue = (IEnumerable <IEntity>)targetProp.GetValue(target);

                    if (sourceValue == null || targetValue == null)
                    {
                        throw new NullReferenceException("Source value or target value is null");
                    }

                    foreach (var child in sourceValue)
                    {
                        target = targetValue.FirstOrDefault(t => t.Id == child.Id);
                        if (target == null)
                        {
                            continue;
                        }
                        child.CheckForRemove(target, context);
                    }

                    var forRemove = sourceValue.Except(targetValue, (x, y) => x.Id == y.Id);
                    foreach (var item in forRemove)
                    {
                        var dbSet = context.GetDbSet(item);
                        if (dbSet != null)
                        {
                            var itemToRemove = dbSet.Find(item.Id);
                            context.Remove(itemToRemove);
                        }
                    }
                }
            }
        }