Last active
April 4, 2017 12:24
-
-
Save leandrocustodio/fdadc0e90fbc7fa813bc5685599c5ed0 to your computer and use it in GitHub Desktop.
Override entity framework savechanges method to automatically set include and modified dates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public override int SaveChanges() | |
{ | |
//verificar adiciona a data atual em todos os elementos que forem adicionados no banco | |
foreach (var entry in ChangeTracker.Entries().Where(entry => entry.Entity.GetType().GetProperty("DataInclusao") != null)) | |
{ | |
if (entry.State == EntityState.Added) | |
{ | |
entry.Property("DateCreated").CurrentValue = DateTime.Now; | |
} | |
else if (entry.State == EntityState.Modified) | |
{ | |
entry.Property("DateCreated").IsModified = false; | |
} | |
} | |
//adicionar a data de modificação em todos os dados que forem atualizados | |
foreach (var entry in ChangeTracker.Entries().Where(entry => entry.Entity.GetType().GetProperty("DataModificacao") != null)) | |
{ | |
if (entry.State == EntityState.Modified) | |
{ | |
entry.Property("DateModified").CurrentValue = DateTime.Now; | |
entry.Property("DateCreated").IsModified = false; | |
} | |
else if (entry.State == EntityState.Added) | |
{ | |
entry.Property("DateModified").IsModified = false; | |
} | |
} | |
return base.SaveChanges(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment