Last active
August 29, 2015 14:21
-
-
Save jesslilly/aec5f154f85e6bda9309 to your computer and use it in GitHub Desktop.
Implementing a Base Class with Entity Framework
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 My.Models.BaseModels | |
{ | |
public class AuditableEntity | |
{ | |
public int Id { get; set; } | |
public DateTime CreatedDt { get; set; } | |
public string CreatedBy { get; set; } | |
public DateTime RevisedDt { get; set; } | |
public string RevisedBy { get; set; } | |
} | |
} |
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 My.Models | |
{ | |
public class Claim : AuditableEntity | |
{ | |
public ClaimType ClaimType { get; set; } | |
public DateTime ClaimDate { get; set; } | |
} | |
} |
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 My.DataAccess | |
{ | |
public class MyDbContext : DbContext | |
{ | |
public MyDbContext() : base("database") // Web.config connection string | |
{ | |
} | |
public DbSet<Claim> Claims { get; set; } | |
protected override void OnModelCreating(DbModelBuilder modelBuilder) | |
{ | |
// To get the Audit fields directly on the Table. | |
modelBuilder.Entity<Claim>().Map(m => m.MapInheritedProperties()).ToTable("Claim"); | |
} | |
public override int SaveChanges() | |
{ | |
var entities = ChangeTracker.Entries().Where(x => x.Entity is AuditableEntity && (x.State == EntityState.Added || x.State == EntityState.Modified)); | |
var currentUsername = HttpContext.Current != null && HttpContext.Current.User != null | |
? HttpContext.Current.User.Identity.Name | |
: "Anonymous"; | |
foreach (var entity in entities) | |
{ | |
if (entity.State == EntityState.Added) | |
{ | |
((AuditableEntity)entity.Entity).CreatedDt = DateTime.Now; | |
((AuditableEntity)entity.Entity).CreatedBy = currentUsername; | |
} | |
((AuditableEntity)entity.Entity).RevisedDt = DateTime.Now; | |
((AuditableEntity)entity.Entity).RevisedBy = currentUsername; | |
} | |
return base.SaveChanges(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment