Example #1
0
        public static Changes <TEntity, TModel> GetChanges <TEntity, TModel>(
            this ICollection <TEntity> entities,
            ICollection <TModel> models,
            Func <TEntity, TModel, bool> compare)
        {
            var result = new Changes <TEntity, TModel>();

            if (entities == null)
            {
                return(result);
            }

            if (models?.Any() != true)
            {
                result.Deleted = entities.ToList();
                return(result);
            }

            result.Deleted = entities
                             .Where(entity => models.All(model => !compare(entity, model)))
                             .ToList();

            var updated = new Dictionary <TEntity, TModel>();

            foreach (var model in models)
            {
                var entity = entities.SingleOrDefault(e => compare(e, model));
                if (entity != null)
                {
                    updated.Add(entity, model);
                }
            }

            result.Updated = updated;

            result.Added = models
                           .Where(model => entities.All(entity => !compare(entity, model)))
                           .ToList();

            return(result);
        }