如何在数据库事务中存储带有当前用户 ID 的“创建者”和“更新者”?

问题描述 投票:0回答:1

我正在尝试存储数据库中发生的所有事务。

我通过在基础中添加列成功存储了“创建于”和“更新于”

using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Models
{
    public class BaseModel : ConfigurationBaseModel
    {
        public DateTime CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
    }
}

然后覆盖保存功能。

public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
    var now = DateTime.UtcNow;

    foreach (var changedEntity in ChangeTracker.Entries())
    {
        if (changedEntity.Entity is BaseModel entity)
        {
            switch (changedEntity.State)
            {
                case EntityState.Added:
                    entity.CreatedAt = now;
                    entity.UpdatedAt = null;
                    break;
                case EntityState.Modified:
                    Entry(entity).Property(x => x.CreatedAt).IsModified = false;
                    entity.UpdatedAt = now;
                    break;
            }
        }
    }

    return base.SaveChangesAsync(cancellationToken);
}

现在我还想在存储当前用户 ID 的位置存储“创建者”和“更新者”。 有办法做到吗?

asp.net database entity-framework asp.net-core .net-core
1个回答
0
投票

我建议使用实体框架拦截器

Entity Framework Core (EF Core) 拦截器可以拦截、修改和/或抑制 EF Core 操作。这包括低级数据库操作(例如执行命令)以及高级操作(例如调用 SaveChanges)。

这里有一篇文章,它演示了如何为您的场景实现拦截器。

© www.soinside.com 2019 - 2024. All rights reserved.