Beispiel #1
0
        public async Task <Unit> Handle(CreateAuditEvents command, CancellationToken cancellationToken)
        {
            var auditEvents = AuditEvent.Create(command, _authentificationContext, _auditSerializer);

            await _dbContext.BulkInsertAsync(auditEvents);

            await _dbContext.SaveChangesAsync();

            return(Unit.Value);
        }
        public async Task Audit()
        {
            if (!_auditConfiguration.AuditDatabaseChanges)
            {
                return;
            }

            var auditDatabaseChanges = _dbContextToAudit.ChangeTracker.Entries()
                                       .Where(entry => entry.Metadata.ClrType.ShouldAudit())
                                       .Select(entry =>
            {
                if (new[] { EntityState.Added, EntityState.Deleted }.Contains(entry.State))
                {
                    var changes = entry.Properties
                                  .Where(property => property.IsTemporary || property.Metadata.PropertyInfo.ShouldAudit())
                                  .ToDictionary(property => property.Metadata.Name, property => entry.State == EntityState.Deleted ? property.OriginalValue : property.CurrentValue);

                    return(BuildAuditDatabaseChange(entry, changes));
                }
                if (entry.State == EntityState.Modified)
                {
                    var propertiesToAudit = entry.Properties.Where(property => property.IsModified && property.Metadata.PropertyInfo.ShouldAudit()).ToList();
                    var changes           = new
                    {
                        PreviousState = propertiesToAudit.ToDictionary(property => property.Metadata.Name, property => property.OriginalValue),
                        NewState      = propertiesToAudit.ToDictionary(property => property.Metadata.Name, property => property.CurrentValue),
                    };

                    return(propertiesToAudit.Any() ? BuildAuditDatabaseChange(entry, changes) : null);
                }

                return(null);
            })
                                       .Where(auditDatabaseChange => auditDatabaseChange != null)
                                       .ToList();

            await _auditDbContext.BulkInsertAsync(auditDatabaseChanges);

            await _auditDbContext.SaveChangesAsync();
        }