Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Implementing a Base Class with Entity Framework
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; }
}
}
namespace My.Models
{
public class Claim : AuditableEntity
{
public ClaimType ClaimType { get; set; }
public DateTime ClaimDate { get; set; }
}
}
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