Beispiel #1
0
        private List <ChangeDetails> CaptureChanges()
        {
            var changes = new List <ChangeDetails>();

            if (!_dbContext.HasChanges())
            {
                return(changes);
            }

            var entries = _dbContext.ChangedEntries();

            foreach (var entry in entries)
            {
                if (entry.State == EntityState.Unchanged || entry.State == EntityState.Detached)
                {
                    continue;
                }

                var entityType = entry.Entity.GetType();

                var entityKey     = _dbContext.GetEntityKey(entry.Entity);
                var changeDetails = new ChangeDetails(entry.State, entityKey, entry.Entity);

                // Capture the property details
                IEnumerable <PropertyDetails> properties = null;

                if (entry.State == EntityState.Modified)
                {
                    properties = entry.OriginalValues.PropertyNames
                                 .Zip(entry.CurrentValues.PropertyNames, (c, o) =>
                                      new PropertyDetails(c, entry.OriginalValues[c], entry.CurrentValues[c]));
                }
                else if (entry.State == EntityState.Added)
                {
                    properties = entry.CurrentValues.PropertyNames
                                 .Select(p => new PropertyDetails(p, null, entry.CurrentValues[p]));
                }
                else if (entry.State == EntityState.Deleted)
                {
                    properties = entry.OriginalValues.PropertyNames
                                 .Select(p => new PropertyDetails(p, null, entry.OriginalValues[p]));
                }

                foreach (var p in properties)
                {
                    changeDetails.Properties.Add(p);
                }

                changes.Add(changeDetails);
            }

            return(changes);
        }