protected virtual AuditEntity GetAuditEntity(EntityEntry entry, OperationType operationType) { var type = entry.Entity.GetType(); var typeName = type.FullName; string entityId = null; var properties = new List <AuditProperty>(); foreach (var property in entry.CurrentValues.Properties) { if (property.IsConcurrencyToken) { continue; } var propertyName = property.Name; var propertyEntry = entry.Property(property.Name); if (property.IsPrimaryKey()) { entityId = entry.State == EntityState.Deleted ? propertyEntry.OriginalValue?.ToString() : propertyEntry.CurrentValue?.ToString(); } var propertyType = property.ClrType.ToString(); string originalValue = null; string newValue = null; if (entry.State == EntityState.Added) { newValue = propertyEntry.CurrentValue?.ToString(); } else if (entry.State == EntityState.Deleted) { originalValue = propertyEntry.OriginalValue?.ToString(); } else if (entry.State == EntityState.Modified) { var currentValue = propertyEntry.CurrentValue?.ToString(); originalValue = propertyEntry.OriginalValue?.ToString(); if (currentValue == originalValue) { continue; } newValue = currentValue; } if (string.IsNullOrWhiteSpace(originalValue)) { // 原值为空,新值不为空则记录 if (!string.IsNullOrWhiteSpace(newValue)) { properties.Add(new AuditProperty(propertyName, propertyType, originalValue, newValue)); } } else { if (!originalValue.Equals(newValue)) { properties.Add(new AuditProperty(propertyName, propertyType, originalValue, newValue)); } } } var auditedEntity = new AuditEntity(typeName, entityId, operationType); auditedEntity.AddProperties(properties); return(auditedEntity); }