如何使用Audit.Net保存实体关系?

时间:2019-02-16 07:29:57

标签: entity-framework audit.net

我正在使用Audit.Net(Audit.EntityFramework),我想知道如何保存实体的关系?

这是我的配置

Audit.Core.Configuration.Setup()
                .UseEntityFramework(x => x
                    .AuditTypeMapper(typeName => typeof(AuditLog))
                    .AuditEntityAction<AuditLog>((ev, ent, auditEntity) =>
                    {
                        auditEntity.Table = ent.Table;
                        auditEntity.AuditDate = DateTime.UtcNow;
                        auditEntity.Action = ent.Action;
                        auditEntity._Changes = ent.Changes;
                        auditEntity._Entries = ev.GetEntityFrameworkEvent().Entries;
                        auditEntity.Success = ev.GetEntityFrameworkEvent().Success;
                        auditEntity._ColumnValues = ent.ColumnValues;
                        auditEntity._PrimaryKey = ent.PrimaryKey;
                    }));

考虑以下关系

public class Blog
{
    public int Id { set; get; }
    public string Title { set; get; }
    public string AuthorName { set; get; }

    public IList<Post> Posts { set; get; }
}

public class Post
{
    public int Id { set; get; }
    public string Title { set; get; }
    public string Content { set; get; }

    public virtual Blog Blog { set; get; }
}

当我删除Blog对象时,我想知道Post的数据是什么。

2 个答案:

答案 0 :(得分:1)

Entity Framework Data Provider为您提供了创建审核表的选项。因此,您必须根据计划创建一个Audit表,并保存所需的相关数据和额外数据。

enter image description here

答案 1 :(得分:1)

如果Blog实例中包含Post,则应该获取有关审计事件的信息。

例如,如果您这样删除:

var post = dbContext.Posts
    .Include(p => p.Blog)
    .First(p => p.Id == 1);
dbContext.Posts.Remove(post);
dbContext.SaveChanges();

并且您将实体对象包括在Audit.EF配置中:

Audit.EntityFramework.Configuration.Setup()
    .ForAnyContext(_ => _
        .IncludeEntityObjects()
    );

您应该能够在AuditEntityAction / CustomAction上获得博客信息:

Audit.Core.Configuration.Setup()
    .UseEntityFramework(x => x
        .AuditTypeMapper(typeName => typeof(AuditLog))
        .AuditEntityAction<AuditLog>((ev, ent, auditEntity) =>
        {
            if (ent.Entity is Post post)
            {
                var blog = post.Blog;
            }
            // OR, if you don't IncludeEntityObjects:
            if (ent.GetEntry().Entity is Post post)
            {

            }
            //...
        }));