Skip to content

Instantly share code, notes, and snippets.

@yuv4ik yuv4ik/IEntity.cs
Last active Aug 23, 2017

Embed
What would you like to do?
EntityFramework database first => generalising timestamps
namespace SameNameSpaceAsAutoGeneratedDbContext
{
public interface IEntity
{
int Id { get; set; }
DateTime CreatedAt { get; set; }
DateTime? UpdatedAt { get; set; }
DateTime? DeletedAt { get; set; }
}
public partial class Customer : IEntity {}
public partial class Product : IEntity {}
}
namespace SameNameSpaceAsAutoGeneratedDbContext
{
public partial class MyDbContext
{
public override Task<int> SaveChangesAsync()
{
AddTimestamps();
return await base.SaveChangesAsync();
}
private void AddTimestamps()
{
var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified || x.State == EntityState.Deleted));
foreach (var entity in entities)
{
switch(entity.State)
{
case EntityState.Added:
((BaseEntity)entity.Entity).CreatedAt = DateTime.UtcNow;
break;
case EntityState.Modified:
((BaseEntity)entity.Entity).UpdatedAt = DateTime.UtcNow;
break;
case EntityState.Deleted:
(BaseEntity)entity.Entity).DeletedAt = DateTime.UtcNow;
break;
}
}
}
}
}
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.