【问题标题】:How To Save Entity Relations With Audit.Net?如何使用 Audit.Net 保存实体关系?
【发布时间】:2019-02-17 13:02:34
【问题描述】:

我正在使用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; }
}

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

【问题讨论】:

    标签: entity-framework audit.net


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果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)
                  {
      
                  }
                  //...
              }));
      

      【讨论】:

      • 我试过了,但它不起作用。它不会保存与column changes 的关系。你能为Audit.EF准备一个简单的控制台应用程序吗?
      • 与外部表的关系不会在列更改上,除非您实际映射关系列(即BlogId)并且该列发生更改。这就是为什么我建议使用 EF 事件 .Entity.GetEntry().Entity
      猜你喜欢
      • 2013-01-12
      • 2011-01-18
      • 1970-01-01
      • 2017-05-05
      • 2015-06-04
      • 2021-06-04
      • 1970-01-01
      • 2021-01-05
      • 2012-01-14
      相关资源
      最近更新 更多