C# 实体框架6(代码优先)实体版本控制和审核
我正在考虑将EntityFramework6.1.1与SQLServer2008R2结合使用 目前,我正在使用代码优先EF功能创建我的模型和数据库。我的基本用例是创建一个特定实体所有变更的日记账(C# 实体框架6(代码优先)实体版本控制和审核,c#,sql-server,entity-framework,entity-framework-6,C#,Sql Server,Entity Framework,Entity Framework 6,我正在考虑将EntityFramework6.1.1与SQLServer2008R2结合使用 目前,我正在使用代码优先EF功能创建我的模型和数据库。我的基本用例是创建一个特定实体所有变更的日记账(ID是关键列),以帮助审计员跟踪所有变更以及变更人。e、 g: |ID|Version|Created Date|Created By|Modified Date|Modified By|Modify Action| ... (rest of entity fields) ---------------
ID
是关键列),以帮助审计员跟踪所有变更以及变更人。e、 g:
|ID|Version|Created Date|Created By|Modified Date|Modified By|Modify Action| ... (rest of entity fields)
-------------------------------------------------------------------------------------------------------
| 4| 12 | 12-Mar-14 | tom | 20-Feb-15 | jack | Update |
| 4| 11 | 12-Mar-14 | tom | 14-Feb-15 | jill | Update |
| 4| 1 | 12-Mar-14 | tom | 12-Mar-14 | tom | Create |
实体框架是否支持这种类型的数据库方案?如果是,我如何设置我的模型/解决方案来促进这一点
另一种方法是拦截对DbContext
上的SaveChanges()
方法的所有调用,并将所有数据库更改记录到一个单独的Audit
表中,但这可能会使检索信息更具挑战性
如果您有任何关于使用SQL Server和EF 6创建审计跟踪的帮助,我们将不胜感激 我使用了您提到的第二种方法,通过重载dbContext SaveChanges()方法: 因此,如果我想记录一个特定的实体,我只需调用重载的SaveChanges&传入一个UserId:
public void Update(StockCatalogueItem entity, int userId)
{
_context.SaveChanges(userId);
}
我还有一个自定义的DoNotLog
属性,用于修饰我不想记录的实体属性。如果不这样做,日志记录可能会生成大量数据,因为每个实体修改相当于一个db条目
[DoNotLog]
public int CreatedBy { get; set; }
GetAuditRecordsForChange
方法检查任何DoNotLog
属性,并返回保存在AuditLogs表中的列表
:
public class AuditLog
{
public int Id { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public AuditEventType EventType { get; set; }
public string TableName { get; set; }
public int EntityId { get; set; }
public string ColumnName { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string IPAddress { get; set; }
public string OriginalValue { get; set; }
public string NewValue { get; set; }
}
你可以看看。它具有审计功能,我使用它将对实体的所有更改记录到XML中。从文件中:
审核日志功能将随时捕获对实体的更改
它们被提交到数据库中。审核日志仅捕获
已更改的实体,并且仅更改这些实体上的属性
这一切都改变了。记录前后值。
AuditLogger.LastAudit是保存此信息的位置,并且存在
ToXml()方法,可以轻松地将AuditLog转换为xml进行
易于储存
可以通过实体上的属性或通过
流畅的配置API
更新:
自2015年以来,不再支持实体框架扩展。
有关此功能,请参阅。我认为这是DDD体系结构中提到的事件源模式的一个很好的候选。您从不更改实体表,而是始终插入 这样,当您需要特定版本时,只需重新播放所有事件,并将它们应用于从版本0到您要查找的版本的实体。可伸缩性可以通过实体快照来解决 第二种方法也是有效的 参考:
这一点的可能重复可能会让您上路:我希望有实体版本,因为这与其他数据库应用程序一致。目前版本控制由monster T-SQL函数管理,我不想实现它,尤其是EF!
public class AuditLog
{
public int Id { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public AuditEventType EventType { get; set; }
public string TableName { get; set; }
public int EntityId { get; set; }
public string ColumnName { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string IPAddress { get; set; }
public string OriginalValue { get; set; }
public string NewValue { get; set; }
}