的DbContext ChangeTracker:身份证加实体的审计 [英] DbContext ChangeTracker: Id of Added Entity for Auditing

查看:497
本文介绍了的DbContext ChangeTracker:身份证加实体的审计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

public override int SaveChanges()
{
    foreach (var changeLog in this.ChangeTracker.Entries()
        .Where(p => p.State == EntityState.Added ||
               p.State == EntityState.Deleted ||
               p.State == EntityState.Modified)
        .SelectMany(entity => AuditRecords(entity)))
    {
        this.ChangeLogs.Add(changeLog);
    }

    return base.SaveChanges();
}

但是,当然,审计更改日志将不包含实体时的EntityState添加(直到调用SaveChanges后)的主键值。我怎样才能获得变更审计目的的主键值?

But, of course, audited change logs will not contain the primary key value of the entity when the EntityState is Added (until after SaveChanges). How can I obtain the primary key value for change auditing purposes?

理查德

推荐答案

我会保存引用实体中的 名单,其中,T> (或阵列,或其他类似结构)和然后的使在调用底层实现的的SaveChanges

I'd store the references to the entities in a List<T> (or an array, or other such structure) and then make the call to the underlying implementation of SaveChanges.

当通话结束,因为你的实体是引用类型(最佳实践表明他们应该是因为它们是可变的),对列表中的这些项目中的主键应该填充,此时您可以通过列表改变实体的审计层。

When the call is complete, because your entities are reference types (best practices indicate they should be as they are mutable), the primary keys on those items in the list should be populated, at which point you can pass the list of changed entities to your audit layer.

此外,似乎您试图添加一个实体,一个实体类型,并把它添加到另一个实体类型的集合(无论是由更新日志暴露);我建议你​​反对这一点。如果您在另一个实体集中进入的项目,做的没有的再利用这些实体,但实例复制到正确的实体类型。

Also, it appears that you are trying to add an entity that one Entity type and add it to another Entity type collection (whatever is exposed by ChangeLogs); I'd recommend against this. If you are entering items in another entity set, do not reuse those entities, but copy the instances to the proper entity type.

这篇关于的DbContext ChangeTracker:身份证加实体的审计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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