EF Core-如何审核价值对象的追踪 [英] EF Core - how to audit trail with value objects

查看:50
本文介绍了EF Core-如何审核价值对象的追踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Entity Framework Core中的某些类实施审计跟踪(跟踪更改的内容,时间和对象).

I'm trying to implement an Audit Trail (track what changed, when and by whom) on a selection of classes in Entity Framework Core.

我当前的实现依赖于重写OnSaveChangesAsync:

My current implementation relies on overriding OnSaveChangesAsync:

public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default) 
{
    var currentUserFullName = _userService.CurrentUserFullName!;

    foreach (var entry in ChangeTracker.Entries<AuditableEntity>())  
    {
        switch (entry.State) 
        {
            case EntityState.Added:
                    entry.Entity.CreatedBy = currentUserFullName;
                    entry.Entity.Created = _dateTime.Now;
                    break;

            case EntityState.Modified:
                    var originalValues = new Dictionary<string, object?>();
                    var currentValues = new Dictionary<string, object?>();

                    foreach (var prop in entry.Properties.Where(p => p.IsModified)) 
                    {
                        var name = prop.Metadata.Name;
                        originalValues.Add(name, prop.OriginalValue);
                        currentValues.Add(name, prop.CurrentValue);
                    }
                    entry.Entity.LastModifiedBy = currentUserFullName;
                    entry.Entity.LastModified = _dateTime.Now;

                    entry.Entity.LogEntries.Add(
                        new EntityEvent(
                            _dateTime.Now,
                            JsonConvert.SerializeObject(originalValues),
                            JsonConvert.SerializeObject(currentValues),
                            currentUserFullName));
                    break;
            }
        }

        return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}

这是简单,干净且非常易于使用的;任何需要审核跟踪的实体都只需继承 AuditableEntity .

This is simple, clean and very easy to use; any entity that needs an audit trail only needs to inherit AuditableEntity.

但是,此方法有一个严格的限制:它无法捕获对导航属性所做的更改.

However, there is a severe limitation to this approach: it cannot capture changes made to navigation properties.

我们的实体充分利用了价值对象,例如EmailAddress:

Our entities make good use of Value Objects, such as an EmailAddress:

public class EmailAddress : ValueObjectBase
{
    public string Value { get; private set; } = null!;

    public static EmailAddress Create(string value) 
    {
        if (!IsValidEmail(value)) 
        {
            throw new ArgumentException("Incorrect email address format", nameof(value));
        }

        return new EmailAddress {
            Value = value
        };
    }
}

... Entity.cs

public EmailAddress Email { get; set; }   

... Entity EF configuration
entity.OwnsOne(e => e.Email);

... Updating
entity.Email = EmailAddress.Create("e@mail.com");

现在,如果用户更改该实体的电子邮件地址,则该实体的状态永远不会更改为已修改.EF Core似乎将ValueObjects作为导航属性来处理,这是分别处理的.

Now if the user changes an email address of this entity, the State of the Entity is never changed to modified. EF Core seems to handle ValueObjects as Navigation Properties, which are handled separately.

所以我认为有几种选择:

So I think there are a few options:

  1. 停止使用ValueObjects作为实体属性.我们仍然可以将它们用作实体构造函数参数,但这将导致其余代码的级联复杂性.也会减少对数据有效性的信任.

  1. Stop using ValueObjects as entity properties. We could still utilize them as entity constructor parameters, but this would cause cascading complexity to the rest of the code. It would also diminish the trust in the validity of the data.

使用SaveChangesAsync停止并构建我们自己的审核处理.同样,这将导致体系结构进一步复杂,并且性能可能会降低.

Stop using SaveChangesAsync and build our own handling for auditing. Again, this would cause further complexity in the architecture and probably be less performant.

ChangeTracker出现了一些奇怪的骇客-听起来很冒险,但理论上可能可行

Some weird hackery to the ChangeTracker - this sounds risky but might work in theory

还有什么事?

推荐答案

如果将值对象映射到数据库中的单个列(例如,电子邮件地址存储在文本列中),则可以改用转换器:

In the case where you value objects are mapped to a single column in the database (e.g. an email address is stored in a text column) you might be able to use converters instead:

var emailAddressConverter = new ValueConverter<EmailAddress, string>(
    emailAddress => emailAddress.Value,
    @string => EmailAddress.Create(@string));

modelBuilder.Entity<User>()
    .Property(user => user.Email)
    .HasConversion(emailAddressConverter);

这应该与您的更改跟踪代码一起很好地工作.

This should work well with your change tracking code.

这篇关于EF Core-如何审核价值对象的追踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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