8
I have a system, in ASP.NET MVC
which implements a form of audit, that when a user enters or updates an object into the database, some information is saved to 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 about how to actually implement, so that save in a table the user who made the insertion or update of this data.
Then the class
public override int SaveChanges()
which I used in the question is not used?– Renan Carlos
It is used yes. The code of the mirror audit goes inside it.
– Leonel Sanches da Silva