Skip to content

Instantly share code, notes, and snippets.

@jyunderwood
Created December 29, 2017 13:43
Show Gist options
  • Save jyunderwood/bf50c35c93a9e3828134462f90ef7675 to your computer and use it in GitHub Desktop.
Save jyunderwood/bf50c35c93a9e3828134462f90ef7675 to your computer and use it in GitHub Desktop.
using CRMProject.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
namespace Infrastructure.Data
{
public class AppDbContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (typeof(ITimestamped).IsAssignableFrom(entityType.ClrType))
{
modelBuilder.Entity(entityType.Name).Property<DateTime>("CreatedAt");
modelBuilder.Entity(entityType.Name).Property<DateTime>("UpdatedAt");
}
}
}
public override int SaveChanges()
{
TimestampChanges();
return base.SaveChanges();
}
private void TimestampChanges()
{
var now = DateTime.Now;
foreach (var entry in ChangeTracker.Entries<ITimestamped>())
{
if (entry.State == EntityState.Added)
{
entry.Property("CreatedAt").CurrentValue = now;
}
if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
{
entry.Property("UpdatedAt").CurrentValue = now;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment