实体框架快照历史记录
本文关键字:记录 历史 快照 框架 实体 | 更新日期: 2023-09-27 18:11:05
我正试图弄清楚如何使用代码优先实体框架并保留某些表的快照历史记录。这意味着,对于我想要跟踪的每个表,我都希望有一个重复的postfixed_History表。每次我对跟踪的表行进行更改时,都会将数据库中的数据复制到历史记录表中,然后将新数据保存到原始表中,并增加"版本"列。
想象一下,我有一张名为Record的桌子。我有一行(ID:1,名称:一,版本:1(。当我将其更改为(ID1:名称:更改,版本:2(时,Record_History表将获得一行(ID:1,名称:一,版本:1(。
我已经看到了很好的例子,并且知道有一些库可以使用Entity Framework来保存更改的审计日志,但我需要在每次修订时对实体进行完整的快照,以便进行SQL报告。
在我的C#中,我有一个基类,我所有的"Tracked"表等价实体类都继承自:
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类,它拥有的每个类型继承自TrackedEntity的DbSet都应该有一个历史对应表,并且每当保存该类型的实体时,都要将原始值从数据库复制到历史表。
因此,在我的DbContext类中,我有一个用于记录的DbSet(以及用于其他实体的更多DbSet(
public DbSet<Record> Records { get; set; }
我已经重写了OnModelCreating方法,以便可以为新的_History表注入映射。然而,我不知道如何使用反射将每个实体的类型传递到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<type>().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是否会生成新的历史记录表。我也不知道如何处理保存,我不确定实体映射是否意味着更改会同时保存在两个表上?我可以在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<TrackedEntity>)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();
}
很抱歉问了这么长的问题,这是一个相当复杂的问题。如有任何帮助,我们将不胜感激。
对于其他想要以相同方式跟踪历史的人,这里是我解决的解决方案。我没能找到一种方法来避免为每个被跟踪的类创建单独的历史类。
我创建了一个基类,我的实体可以从中继承:
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; }
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<TrackedEntity>())
{
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 e.g. 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>(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<T>)property.GetValue(this, null)).Add(value);
}
..........
}
然后,每当我保存更改时,我都会使用新方法,并传入当前用户名。我希望我可以避免使用_History类,因为它们需要与主实体类一起维护,而且很容易忘记。
简单的方法是SQLserver CDC。点击此处了解更多信息http://technet.microsoft.com/en-us/library/bb522489(v=sql.105(.aspx
如果使用SQL Server 2016
<或CCD_ 2。
https://learn.microsoft.com/en-us/sql/relational-databases/tables/temporal-tables?view=sql-服务器-ver15
来自文件:
提供内置支持的数据库功能关于在任何时间点存储在表中的数据的信息而不仅仅是当前时刻正确的数据。时态是ANSI SQL 2011中引入的数据库功能。
我在这里写了一个完整的指南,如何在没有任何第三方库的情况下使用实体框架核心实现它。应该可以使用实体框架,但不进行测试。
https://stackoverflow.com/a/64244548/3850405