EF 6及更高版本是否提供更好的审核与数据交互的方法? [英] Does EF 6 and higher offer better ways of auditing interactions with the data?

查看:62
本文介绍了EF 6及更高版本是否提供更好的审核与数据交互的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是开发一种审核数据读取/编辑/删除数据的方法。我用EF搜索了如何做到这一点。我在CodeProject上发现了这篇博文,

使用实体框架第1部分实施审计跟踪
。然而,这篇文章是在2009年写的。我相信它会起作用,但我想知道如果使用EF 6及更高版本,可能有更好的方法来做到这一点?



Rod

I've been tasked with developing a means of auditing reads/edits/deletes of data from our databases. I did a search on how to do this with EF. I found this blog post on CodeProject, Implementing Audit Trail using Entity Framework Part-1. However, the article was written back in 2009. I'm sure it will work, but I'm wondering if using EF 6 and higher, there might be better ways of doing this?


Rod

推荐答案

嗨Rod at W ork,

EF6使用 DbContext 而不是OjbectContext,您可以使用
ChangeTracker
SaveChanges 覆盖中查找自定义类型的添加/修改实体。如下所示:

EF6 use DbContext instead of OjbectContext, you could use ChangeTracker in SaveChanges override to find added/modified entities of custom type. like below:

public interface IAuditedEntity {
  string CreatedBy { get; set; }
  DateTime CreatedAt { get; set; }
  string LastModifiedBy { get; set; }
  DateTime LastModifiedAt { get; set; }
}

public override int SaveChanges() {
  var addedAuditedEntities = ChangeTracker.Entries<IAuditedEntity>()
    .Where(p => p.State == EntityState.Added)
    .Select(p => p.Entity);

  var modifiedAuditedEntities = ChangeTracker.Entries<IAuditedEntity>()
    .Where(p => p.State == EntityState.Modified)
    .Select(p => p.Entity);

  var now = DateTime.UtcNow;

  foreach (var added in addedAuditedEntities) {
    added.CreatedAt = now;
    added.LastModifiedAt = now;
  }

  foreach (var modified in modifiedAuditedEntities) {
    modified.LastModifiedAt = now;
  }

  return base.SaveChanges();
}

祝你好运,

Cole Wu


这篇关于EF 6及更高版本是否提供更好的审核与数据交互的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆