private void OnAfterSaveChanges(List <AuditEntry> auditEntries) { if (auditEntries == null || auditEntries.Count == 0) { return; } foreach (var auditEntry in auditEntries) { foreach (var prop in auditEntry.TemporaryProperties) { if (prop.Metadata.IsPrimaryKey()) { auditEntry.IdsAlterados[prop.Metadata.Name] = prop.CurrentValue; } else { auditEntry.ValoresNovos[prop.Metadata.Name] = prop.CurrentValue; } } Auditoria.Add(auditEntry.ToAudit()); } SaveChanges(); }
private List <AuditEntry> OnBeforeSaveChanges() { ChangeTracker.DetectChanges(); var auditEntries = new List <AuditEntry>(); foreach (var entry in ChangeTracker.Entries()) { if (entry.Entity is Auditoria || entry.State == EntityState.Detached || entry.State == EntityState.Unchanged) { continue; } var auditEntry = new AuditEntry(entry) { Tabela = entry.Metadata.Relational().TableName.ToUpper(), Usuario = _variables.UserName }; auditEntries.Add(auditEntry); foreach (var property in entry.Properties) { if (property.IsTemporary) { auditEntry.TemporaryProperties.Add(property); continue; } string propertyName = property.Metadata.Name; if (property.Metadata.IsPrimaryKey()) { auditEntry.IdsAlterados[propertyName] = property.CurrentValue; continue; } switch (entry.State) { case EntityState.Added: auditEntry.ValoresNovos[propertyName] = property.CurrentValue; break; case EntityState.Deleted: auditEntry.ValoresAntigos[propertyName] = property.OriginalValue; break; case EntityState.Modified: if (property.IsModified) { if ((property.CurrentValue != null && property.OriginalValue != null) && (!property.CurrentValue.Equals(property.OriginalValue))) { auditEntry.ValoresAntigos[propertyName] = property.OriginalValue; auditEntry.ValoresNovos[propertyName] = property.CurrentValue; } } break; } } } // Save audit entities that have all the modifications foreach (var auditEntry in auditEntries.Where(_ => !_.HasTemporaryProperties)) { Auditoria.Add(auditEntry.ToAudit()); } // keep a list of entries where the value of some properties are unknown at this step return(auditEntries.Where(_ => _.HasTemporaryProperties).ToList()); }