I have a system, in ASP.NET MVC
that implements an audit form, that when a user inserts or updates an object in the database, some information is saved in an audit table automatically.
The interface, which I want to implement is:
public interface IEntidade
{
DateTime DataCriacao { get; set; }
String UsuarioCriacao { get; set; }
DateTime UltimaModificacao { get; set; }
String UsuarioModificacao { get; set; }
}
I also have an example of SaveChanges();
in my class that inherits from DbContext
public override int SaveChanges()
{
try
{
var currentTime = DateTime.Now;
foreach (var entry in ChangeTracker.Entries().Where(e => e.Entity != null &&
typeof(IEntidadePrimitiva).IsAssignableFrom(e.Entity.GetType())))
{
if (entry.State == EntityState.Added)
{
if (entry.Property("DataCriacao") != null)
{
entry.Property("DataCriacao").CurrentValue = currentTime;
}
if (entry.Property("UsuarioCriacao") != null)
{
entry.Property("UsuarioCriacao").CurrentValue = HttpContext.Current != null ? HttpContext.Current.User.Identity.Name : "Usuario";
}
}
if (entry.State == EntityState.Modified)
{
entry.Property("DataCriacao").IsModified = false;
entry.Property("UsuarioCriacao").IsModified = false;
if (entry.Property("UltimaModificacao") != null)
{
entry.Property("UltimaModificacao").CurrentValue = currentTime;
}
if (entry.Property("UsuarioModificacao") != null)
{
entry.Property("UsuarioModificacao").CurrentValue = HttpContext.Current != null ? HttpContext.Current.User.Identity.Name : "Usuario";
}
}
}
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionsMessage = string.Concat(ex.Message, "Os erros de validações são: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionsMessage, ex.EntityValidationErrors);
}
}
But what I am in doubt, is how to actually implement, so you can save the user who has inserted or updated this data into a table.