entity framework快照历史记录

我试图弄清楚如何使用Code First Entity Framework并保留某些表的快照历史记录。 这意味着对于我想要跟踪的每个表,我希望有一个后缀为_History的重复表。 每次我对跟踪的表行进行更改时,数据库中的数据都会在将新数据保存到原始表之前复制到历史表中,并且版本列会递增。

所以想象我有一个名为Record的表。 我有一排(ID:1,名称:一,版本:1)。 当我将其更改为(ID1:Name:Changed,Version:2)时,Record_History表获取一行(ID:1,Name:One,Version:1)。

我已经看到了很好的示例,并且知道有些库可以使用Entity Framework保留更改的审核日志,但我需要在SQL报告的每个修订版本中提供实体的完整快照。

在我的C#中,我有一个基类,我的所有“Tracked”表等效实体类都inheritance自:

public abstract class TrackedEntity { [Column(TypeName = "varchar")] [MaxLength(48)] [Required] public string ModifiedBy { get; set; } [Required] public DateTime Modified { get; set; } public int Version { get; set; } } 

我的一个实体类的示例是:

 public sealed class Record : TrackedEntity { [Key] public int RecordID { get; set; } [MaxLength(64)] public string Name { get; set; } } 

现在,对于我坚持的部分。 我想避免为我制作的每个实体打字并维护一个单独的_History类。 我想做一些聪明的事情来告诉我的DbContext类,它拥有的每个inheritance自TrackedEntity的类型的DbSet应该有一个历史对应表,并且每当保存该类型的实体时,将原始值从数据库复制到历史表。

所以在我的DbContext类中,我的记录有一个DbSet(我的其他实体有更多的DbSet)

 public DbSet Records { get; set; } 

我已经重写了OnModelCreating方法,因此我可以为新的_History表注入映射。 但是我无法弄清楚如何使用reflection将每个实体的Type传递给DbModelBuilder。

  protected override void OnModelCreating(DbModelBuilder modelBuilder) { //map a history table for each tracked Entity type PropertyInfo[] properties = GetType().GetProperties(); foreach (PropertyInfo property in properties.Where(p => p.PropertyType.IsGenericType && p.PropertyType.Name.StartsWith("DbSet") && p.PropertyType.GetGenericArguments().Length > 0 && p.PropertyType.GetGenericArguments()[0].IsSubclassOf(typeof(TrackedEntity)))) { Type type = property.PropertyType.GetGenericArguments()[0]; modelBuilder.Entity().Map(m => //code breaks here, I cannot use the type variable it expects a hard coded Type { m.ToTable(type.Name + "_History"); m.MapInheritedProperties(); }); } } 

我甚至不确定使用像这样的modelBuilder甚至会生成新的History表。 我也不知道如何处理保存,我不确定实体映射是否意味着更改然后保存在两个表中? 我可以在我的DbContext中创建一个可以循环我的实体的SaveChanges方法,但我不知道如何将实体保存到第二个表。

  public int SaveChanges(string username) { //duplicate tracked entity values from database to history tables PropertyInfo[] properties = GetType().GetProperties(); foreach (PropertyInfo property in properties.Where(p => p.PropertyType.IsGenericType && p.PropertyType.Name.StartsWith("DbSet") && p.PropertyType.GetGenericArguments().Length > 0 && p.PropertyType.GetGenericArguments()[0].IsSubclassOf(typeof(TrackedEntity)))) { foreach (TrackedEntity entity in (DbSet)property.GetValue(this, null)) { entity.Modified = DateTime.UtcNow; entity.ModifiedBy = username; entity.Version += 1; //Todo: duplicate entity values from database to history tables } } return base.SaveChanges(); } 

很抱歉这么长的问题,这是一个非常复杂的问题。 任何帮助,将不胜感激。

对于其他想要以同样方式跟踪历史记录的人来说,这是我解决的解决方案。 我没有找到办法避免为每个跟踪类创建单独的历史记录类。

我创建了一个我的实体可以inheritance的基类:

 public abstract class TrackedEntity { [Column(TypeName = "varchar")] [MaxLength(48)] [Required] public string ModifiedBy { get; set; } [Required] public DateTime Modified { get; set; } public int Version { get; set; } } 

对于每个实体,我创建一个普通的实体类,但从我的基础inheritance:

 public sealed class Record : TrackedEntity { [Key] public int RecordID { get; set; } [MaxLength(64)] public string Name { get; set; } public int RecordTypeID { get; set; } [ForeignKey("RecordTypeID")] public virtual RecordType { get; set; } } 

对于每个实体,我还创建了一个历史类(始终是一个精确的副本,但移动了Key列,并删除了所有外键)

 public sealed class Record_History : TrackedEntity { [Key] public int ID { get; set; } public int RecordID { get; set; } [MaxLength(64)] public string Name { get; set; } public int RecordTypeID { get; set; } } 

最后,我在上下文类中创建了SaveChanges方法的重载,这会根据需要更新历史记录。

 public class MyContext : DbContext { .......... public int SaveChanges(string username) { //Set TrackedEntity update columns foreach (var entry in ChangeTracker.Entries()) { if (entry.State != EntityState.Unchanged && !entry.Entity.GetType().Name.Contains("_History")) //ignore unchanged entities and history tables { entry.Entity.Modified = DateTime.UtcNow; entry.Entity.ModifiedBy = username; entry.Entity.Version += 1; //add original values to history table (skip if this entity is not yet created) if (entry.State != EntityState.Added && entry.Entity.GetType().BaseType != null) { //check the base type exists (actually the derived type eg Record) Type entityBaseType = entry.Entity.GetType().BaseType; if (entityBaseType == null) continue; //check there is a history type for this entity type Type entityHistoryType = Type.GetType("MyEntityNamespace.Entities." + entityBaseType.Name + "_History"); if (entityHistoryType == null) continue; //create history object from the original values var history = Activator.CreateInstance(entityHistoryType); foreach (PropertyInfo property in entityHistoryType.GetProperties().Where(p => p.CanWrite && entry.OriginalValues.PropertyNames.Contains(p.Name))) property.SetValue(history, entry.OriginalValues[property.Name], null); //add the history object to the appropriate DbSet MethodInfo method = typeof(MyContext).GetMethod("AddToDbSet"); MethodInfo generic = method.MakeGenericMethod(entityHistoryType); generic.Invoke(this, new [] { history }); } } } return base.SaveChanges(); } public void AddToDbSet(T value) where T : class { PropertyInfo property = GetType().GetProperties().FirstOrDefault(p => p.PropertyType.IsGenericType && p.PropertyType.Name.StartsWith("DbSet") && p.PropertyType.GetGenericArguments().Length > 0 && p.PropertyType.GetGenericArguments()[0] == typeof(T)); if (property == null) return; ((DbSet)property.GetValue(this, null)).Add(value); } .......... } 

然后每当我保存更改时,我都会使用新方法,并传入当前用户名。 我希望我可以避免使用_History类,因为它们需要与主实体类一起维护,并且很容易忘记。

简单的方法是SQLserver CDC。 更多信息http://technet.microsoft.com/en-us/library/bb522489(v=sql.105).aspx