Пример #1
0
        public static List <EntityChangeTracker> GetChangesMade <TEntity>(DbContext _db, TEntity theEntity) where TEntity : class, new()
        {
            List <EntityChangeTracker> comparisonList = new List <EntityChangeTracker>();

            // Get list of entities that are marked as modified
            List <DbEntityEntry> modifiedEntityList =
                _db.ChangeTracker.Entries().Where(x => x.State == EntityState.Modified).ToList();

            foreach (DbEntityEntry entity in modifiedEntityList)
            {
                if (entity.Entity == theEntity)
                {
                    DbPropertyValues propertyValues = entity.OriginalValues;


                    foreach (String propertyName in propertyValues.PropertyNames)
                    {
                        object objOriginal   = propertyValues[propertyName];
                        string originalValue = (objOriginal != null ? objOriginal.ToString() : null);
                        object objNew        = entity.Entity.GetType().GetProperty(propertyName).GetValue(entity.Entity);
                        string newValue      = (objNew != null ? objNew.ToString() : null);

                        if (originalValue != newValue)
                        {
                            EntityChangeTracker ect = new EntityChangeTracker();
                            ect.OriginalValue = originalValue;
                            ect.NewValue      = newValue;
                            ect.PropertyName  = propertyName;

                            comparisonList.Add(ect);
                        }
                    }
                }
            }

            return(comparisonList);
        }