- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试弄清楚如何使用 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# 中,我有一个基类,我的所有“跟踪”表等效实体类都继承自该基类:
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 类它拥有的每个 DbSet 都具有从 TrackedEntity 继承的类型应该有一个历史对应表,并且每当保存该类型的实体时,将原始值从数据库复制到历史表。
所以在我的 DbContext 类中,我有一个 DbSet 用于我的记录(还有更多 DbSet 用于我的其他实体)
public DbSet<Record> Records { get; set; }
我已经覆盖了 OnModelCreating 方法,因此我可以为新的 _History 表注入(inject)映射。但是我不知道如何使用反射将每个实体的类型传递到 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; }
}
我为每个实体创建一个普通的实体类,但继承 self 的基类:
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 类,因为它们需要与主要实体类一起维护,并且很容易被遗忘。
关于c# - Entity Framework 快照历史,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24534607/
这个问题在这里已经有了答案: 10年前关闭。 Possible Duplicates: What is a framework? What does it do? Why do we need a f
我在按照 http://msdn.microsoft.com/en-us/data/jj591621.aspx 处的 Microsoft Data Developer 过程启用代码优先迁移时遇到了一些
我正在从 迁移项目 Entity Framework 4.3 在 .net 4 上运行到 Entity Framework 5 在 .net 4.5 上运行。在不做任何更改的情况下,当我尝试运行该项目
我正在使用 Entity Framework 6 并使用 EntityFramework Extended 来执行一些批量更新和批量删除。批量更新和批量删除工作正常,但我还需要知道更新/删除的实体(即
我在实体上添加了一个列,然后从模型中生成数据库或构建解决方案,然后收到一条消息,提示我刚添加的新列未映射。该数据库以前是从模型创建的,没有错误。 当我右键单击Entity并选择Table Mappin
每次我尝试运行我的代码时都会崩溃,因为我尝试启动函数以调用 SDK 的任何部分。 我在构建过程中包含了 FoundationSDK: 并且我在头文件中包含了对 SDK 的引用: 但是每次我运行这个,我
我以前能够毫无问题地提交我的申请。我的工作流程中唯一改变的部分是使用 Sourcetree。在对以下框架进行更新后,我在提交到 iOS App Store 时收到此警告。我还收到一封电子邮件,其中包含
假设我为 Asp.NET Web 应用程序安装了 .NET Framework 2.0、3.0、3.5。 我意识到 Framework 3.0 和 3.5 只是 Framework 2 的扩展,不太清
是否有 SaveChanges 事件在保存更改后但在更新更改跟踪器之前触发? 我正在使用 EF 6。 我需要在某个实体的状态发生变化时执行任务。 我已经覆盖了 SaveChanges 来设置它。我可以
我正在使用一个现有的数据库,并且我已经将其中一个表映射为一个实体(因为我需要映射一个外键)。 因此,在初始化此数据库时,我希望 EF 忽略此实体,因为它已经存在。 我该怎么做? 最佳答案 您应该使用
我有 3 个表需要与 Entity Framework 进行映射,但我不确定解决此问题的正确方法。这是我的 3 个实体: public class User { [Key] public
我首先使用 VS 2010 和 Entity Framework 代码(版本 6)。我有两个实体,每个实体都在自己的上下文中,我想在它们之间创建一对多关系。 上下文 1 具有以下实体: public
我知道 EF 在 CodePlex 上是开源的,但我没有看到当前发布的 5.0 版本的分支。我在哪里可以得到这个源代码? 最佳答案 没有。他们只开源了 post 5 版本。第一次签到可能足够接近,但再
我们目前有一个数据库很大的系统,存储过程既用于CUD又用于查询。数据集用于从 SP 查询中检索结果。 现在我们正在研究使用 Entity Framework 针对同一个数据库开发另一个项目。在查询数据
我有一个每 10 秒运行一次的 Windows 服务......每次运行时,它都会获取一些测试数据,对其进行修改并使用 EntityFramework 将其保存到数据库中。但是,在每一秒运行时,当我尝
我对在我们的场景中仅将 Entity Framework 与存储过程一起使用的合理性有疑问。 我们计划拥有一个 N 层架构,包括 UI、BusinessLayer (BLL)、DataAccessLa
当我使用 Entity Framework 时,我想在上下文中查询出一条记录并将其添加到具有相同架构的另一个上下文中,在查询出记录后,我将其从上下文中分离出来,但是相关实体都没有了,是吗?有什么办法解
我正在使用 Entity Framework 5 构建 ASP.Net MVC4 Web 应用程序。我必须使用现有的 sql server 数据库,但也想使用 Code First,所以我遵循了本教程
在 Entity Framework 4.0 中使用 T4 模板创建 POCO 会丢失什么?为什么使用 Entity Framework 4.0 时的默认行为不创建 POCO? 最佳答案 你会失去很多
我在网上使用 Repository Pattern 和 EF 看了很多例子。但他们都没有真正谈到与相关实体的合作。 就像说用户可以有多个地址。 IUserRepository User CreateU
我是一名优秀的程序员,十分优秀!