Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* Exemplo:
O método SaveChanges foi sobrescrito para verificar se irá persistir instâncias de entidades que implementam
a interface IAuditableEntity.
Para facilitar, utilizo uma class base chamada EntityBase que implementa essa interface,
e implementa também IValidatableObject.
*/
public interface IAuditableEntity
{
DateTime DataCadastro { get; set; }
DateTime? DataAlteracao { get; set; }
string Modifier { get; set; }
}
public abstract class EntityBase : IAuditableEntity, IValidatableObject
{
[Key]
public long Id { get; set; }
public DateTime DataCadastro { get; set; }
public DateTime? DataAlteracao { get; set; }
public string Modifier { get; set; }
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield return ValidationResult.Success;
}
}
public class Usuario : EntityBase
{
[Required, StringLength(50)]
public string Login { get; set; }
[Required, StringLength(100)]
public string Senha { get; set; }
[Required, StringLength(50)]
public string Salt { get; set; }
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Login == Senha)
yield return new ValidationResult("Login/Senha devem ser diferentes", new[] "Login", "Senha");
else yield return ValidationResult.Success;
}
}
public class MyContext : DbContext
{
private readonly string _modifier; //informações customizadas
public MyContext(string modifier)
{
_modifier = modifier;
}
public MyContext()
: this("") /* sem modificador*/
{
}
public override int SaveChanges()
{
var auditables = ChangeTracker.Entries().Where(x => x.Entity is IAuditableEntity);
foreach (var entity in auditables)
{
var auditableEntity = (IAuditableEntity)entity.Entity;
switch (entity.State)
{
case EntityState.Added:
if (auditableEntity.DataCadastro == default(DateTime))
auditableEntity.DataCadastro = DateTime.Now;
break;
case EntityState.Modified:
auditableEntity.DataAlteracao = DateTime.Now;
break;
}
auditableEntity.Modifier = _modifier;
}
return base.SaveChanges();
}
/* Código omitido ...*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.