One common need among database creation is auditing. Fields likeDateCreated, DateLastUpdated, etc...etc... Well with EF Code First,there is one pretty easy way of getting it accomplished.
EF Code First uses a class that inherits from a DbContext to storeall of the different Entities used in your application. It lookssomething like...
public class MyContext : DbContext{public DbSet<MyEntity> MyEntities { get; set; }}
By overriding the SaveChanges method like this...
public override int SaveChanges(){// var auditUser = HttpContext.Current.User.Identity.Name;DateTime auditDate = DateTime.UtcNow;foreach (DbEntityEntry<IAuditable> entry in ChangeTracker.Entries<IAuditable>()){if (entry.State == EntityState.Added){entry.Entity.CreatedOn = auditDate;entry.Entity.ModifiedOn = auditDate;// entry.Entity.CreatedBy = auditUser;// entry.Entity.ModifiedBy = auditUser;}else if (entry.State == EntityState.Modified){entry.Entity.ModifiedOn = auditDate;// entry.Entity.ModifiedBy = auditUser;}}return base.SaveChanges();}
You can uncomment the two user fields and update the user with this code as well.
联系客服