internal void WriteAudit(SADFMEntities context, Guid lastUpdateAccountId) { if (!context.ChangeTracker.HasChanges()) { return; } var allChanges = context.ChangeTracker.Entries(); foreach (DbEntityEntry ee in allChanges) { if (ee.State == System.Data.Entity.EntityState.Unchanged) { continue; } if (ee.State == System.Data.Entity.EntityState.Deleted) { //Deletes should be tracked by the parent object or status change continue; } ObjectContext ox = ((IObjectContextAdapter)context).ObjectContext; ObjectStateEntry ose = ox.ObjectStateManager.GetObjectStateEntry(ee.Entity); Guid pkid = Guid.Empty; if (ose.EntityKey.EntityKeyValues != null) { EntityKeyMember member = ose.EntityKey.EntityKeyValues[0]; pkid = (Guid)member.Value; } bool added = ee.State == System.Data.Entity.EntityState.Added; string tableName = ose.EntitySet.Name; System.Data.Entity.Infrastructure.DbPropertyValues original = null; if (!added) { original = ee.OriginalValues; } System.Data.Entity.Infrastructure.DbPropertyValues current = null; if (ee.State != System.Data.Entity.EntityState.Deleted) { current = ee.CurrentValues; } foreach (string property in current.PropertyNames) { object originalValue = original == null ? null : original.GetValue <object>(property); object currentValue = current == null ? null : current.GetValue <object>(property); if (originalValue == null && currentValue == null) { continue; } if (originalValue == null || currentValue == null || originalValue.ToString() != currentValue.ToString()) { context.Audits.Add(new Data.Audit { TableName = tableName, ChangeTypeId = DataAccess.ListItem.GetListItem("ChangeType", added ? "Insert" : "Update").GUID, AccountId = lastUpdateAccountId, FieldName = property, OldValue = originalValue == null ? null : originalValue.ToString().Substring(0, originalValue.ToString().Length > 1000 ? 1000 : originalValue.ToString().Length), NewValue = currentValue == null ? null : currentValue.ToString().Substring(0, currentValue.ToString().Length > 1000 ? 1000 : currentValue.ToString().Length), PrimaryKeyId = pkid, UpdateDate = DateTime.Now }); } } } }