Implementing a Base Class with Entity Framework
I want to add a bunch of audit fields to all of my tables. Here's how I did it with a base class. Note that the base class must have a key column. The subclass does not have an ID explicitly; it inherits the ID column from the base class.
The call to MapInheritedProperties will put the inherited properties directly on the subclass table.
The call to MapInheritedProperties will put the inherited properties directly on the subclass table.
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
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 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 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(); | |
} | |
} | |
} |
Comments
Post a Comment