Assuming you are using EF to add the information about which user is updating records, the easiest way to capture that information is to have EF perform a 2-step process (UPDATE, DELETE) on the data you wish to delete. You will then need to interpret the two audit rows as part of the same operation.
There is a much more involved solution that "might" work, but I have not tested it. There is more information available below if you wish to explore it.
Another option altogether is to abandon trigger auditing (which is problematic for this very reason) and use Entity Framework instead. Below is an example of how one might accomplish this by overriding the SaveChanges
method:
public virtual IEnumerable<System.Data.Entity.Infrastructure.DbEntityEntry> ChangedEntries()
{
return ChangeTracker.Entries().Where(x =>
x.State == EntityState.Added ||
x.State == EntityState.Deleted ||
x.State == EntityState.Modified);
}
public virtual int SaveChanges(string userName)
{
var changes = ChangedEntries();
foreach (var entry in changes)
{
var eventType = entry.State == EntityState.Added ? "A" : entry.State == EntityState.Deleted ? "D" : "U";
var entityType = ObjectContext.GetObjectType(entry.Entity.GetType()).Name;
var oldValues = entry.State == EntityState.Added ? null : JsonConvert.SerializeObject(entry.OriginalValues.ToObject());
var newValues = entry.State == EntityState.Deleted ? null : JsonConvert.SerializeObject(entry.CurrentValues.ToObject());
oldValues = oldValues?.Substring(0, Math.Min(oldValues.Length, 4000));
newValues = newValues?.Substring(0, Math.Min(newValues.Length, 4000));
AuditItems.Add(
new AuditItem
{
EventTime = DateTime.Now,
UserName = userName,
EntityType = entityType,
EventType = eventType,
OldValues = oldValues,
NewValues = newValues
}
);
}
return base.SaveChanges();
}
INSERTED
pseudo table, as you said, but not anUPDATED
one. There's theDELETED
pseudo table too – Lamaksuser_sname()
is the account name who run the query. – Alex Kudryashevsuser_sname()
will only return the login for the whatever account connected to SQL Server. If it is being used by a web service, it won't identify the end user. – yelxe