Skip to content

Instantly share code, notes, and snippets.

@osmyn
Last active March 29, 2018 19:25
Show Gist options
  • Save osmyn/0557ca1394447e90ae7efa0a8ca2d181 to your computer and use it in GitHub Desktop.
Save osmyn/0557ca1394447e90ae7efa0a8ca2d181 to your computer and use it in GitHub Desktop.
I often create an override in EF for save changes that handles read only and updatable entities
public override int SaveChanges()
{
var changed = ChangeTracker.Entries()
.Where(e => e.State == EntityState.Modified || e.State == EntityState.Added);
foreach (var item in changed)
{
if (item.Entity is IReadOnlyEntity)
{
item.State = EntityState.Unchanged;
}
else if (item.Entity is IUpdateableEntity)
{
((IUpdateableEntity) item).LastUpdated = DateTime.UtcNow;
}
}
return base.SaveChanges();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment