Created
December 29, 2017 13:43
-
-
Save jyunderwood/bf50c35c93a9e3828134462f90ef7675 to your computer and use it in GitHub Desktop.
This file contains 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
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