Last active
August 29, 2015 14:17
-
-
Save wholroyd/edd6aa2e49c2bb5da71b to your computer and use it in GitHub Desktop.
EntityFramework SavingChanges event
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
namespace Foundation.Data.Sql.EntityFramework | |
{ | |
using System; | |
using System.Data.Entity; | |
using System.Data.Entity.Infrastructure; | |
using Foundation.Core.Abstractions; | |
using Foundation.Infrastructure.Common.Data; | |
public class FoundationContext : DbContext | |
{ | |
public FoundationContext() | |
: base("DefaultConnection") | |
{ | |
var objectContext = ((IObjectContextAdapter)this).ObjectContext; | |
objectContext.SavingChanges += (sender, args) => | |
{ | |
var now = DateTime.UtcNow; | |
foreach (var entry in this.ChangeTracker.Entries<IEntityStorable>()) | |
{ | |
var entity = entry.Entity; | |
switch (entry.State) | |
{ | |
case EntityState.Added: | |
entity.CreatedDate = now; | |
entity.UpdatedDate = now; | |
break; | |
case EntityState.Modified: | |
entity.UpdatedDate = now; | |
break; | |
} | |
} | |
this.ChangeTracker.DetectChanges(); | |
}; | |
} | |
public DbSet<Models.Environment> Environments { get; set; } | |
public static FoundationContext Create() | |
{ | |
return new FoundationContext(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment