use*_*618 4 c# entity-framework ef-code-first
我试图弄清楚如何使用 Code First Entity Framework 并保留某些表的快照历史记录。这意味着对于我想要跟踪的每个表,我希望有一个后缀为 _History 的重复表。每次我对跟踪表行进行更改时,在新数据保存到原始表之前,数据库中的数据都会复制到历史表中,版本列会增加。
所以想象我有一个名为 Record 的表。我有一排(ID:1,名称:一,版本:1)。当我将其更改为 (ID1:Name:Changed,Version:2) 时,Record_History 表将获得一行 (ID:1,Name:One,Version:1)。
我已经看到了很好的例子,并且知道有一些库可以使用实体框架来保存更改的审计日志,但我需要在 SQL 报告的每个修订版中获得实体的完整快照。
在我的 C# 中,我有一个基类,我所有的“跟踪”表等效实体类都继承自:
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; }
}
Run Code Online (Sandbox Code Playgroud)
我的实体类之一的示例是:
public sealed class Record : TrackedEntity
{
[Key]
public int RecordID { get; set; }
[MaxLength(64)]
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在对于我坚持的部分。我想避免为我创建的每个实体输入和维护一个单独的 _History 类。我想做一些聪明的事情来告诉我的 DbContext 类它拥有的每个 DbSet 类型继承自 TrackedEntity 都应该有一个历史对应表,并且每当保存该类型的实体时,将原始值从数据库复制到历史表。
因此,在我的 DbContext 类中,我的记录有一个 DbSet(以及其他实体的更多 DbSet)
public DbSet<Record> Records { get; set; }
Run Code Online (Sandbox Code Playgroud)
我已经覆盖了 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();
});
}
}
Run Code Online (Sandbox Code Playgroud)
我什至不确定像这样使用模型构建器是否会生成新的历史记录表。我也不知道如何处理保存,我不确定实体映射是否意味着更改会保存在两个表上?我可以在我的 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();
}
Run Code Online (Sandbox Code Playgroud)
抱歉问了这么长的问题,这是一个相当复杂的问题。任何帮助,将不胜感激。
对于想要以相同方式跟踪历史的任何其他人,这是我解决的解决方案。我没有设法避免为每个跟踪类创建单独的历史类。
我创建了一个基类,我的实体可以从中继承:
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; }
}
Run Code Online (Sandbox Code Playgroud)
对于每个实体,我创建了一个普通的实体类,但从我的基类继承:
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; }
}
Run Code Online (Sandbox Code Playgroud)
对于每个实体,我还创建了一个历史类(总是一个精确的副本,但移动了 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; }
}
Run Code Online (Sandbox Code Playgroud)
最后,我在上下文类中创建了 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);
}
..........
}
Run Code Online (Sandbox Code Playgroud)
然后每当我保存更改时,我都会使用新方法,并传入当前用户名。我希望我可以避免使用 _History 类,因为它们需要与主实体类一起维护,并且很容易忘记。
| 归档时间: |
|
| 查看次数: |
2959 次 |
| 最近记录: |