【问题标题】:How to override the ef core to write data automatically or log to file?如何覆盖 ef 核心以自动写入数据或记录到文件?
【发布时间】:2020-08-02 16:19:13
【问题描述】:

我正在使用 asp.net core + ef core。我可以向数据库添加删除获取或更新数据。

但是当我执行这些操作时,它可以自动将用户信息和datetime 记录到文件或数据库中吗?

如果我正在更新数据,数据将自动更新 LastModifiedDateTimeModifyUserId 属性。

或将其记录到文件中?

例如: 如果我更新数据库

await _context.SaveChangesAsync(cancellationToken);

我可以这样做:

public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
    {
        foreach (var entry in ChangeTracker.Entries<AuditableEntity>())
        {
            switch (entry.State)
            {
                case EntityState.Added:
                    entry.Entity.CreatedBy = _currentUserService.UserId;
                    entry.Entity.Created = _dateTime.Now;
                    break;
                case EntityState.Modified:
                    entry.Entity.LastModifiedBy = _currentUserService.UserId;
                    entry.Entity.LastModified = _dateTime.Now;
                    break;
            }
        }

        return base.SaveChangesAsync(cancellationToken);
    }

不需要我指定属性而是覆盖它以自动记录它?

如何设置每个实体的属性? 然后我就可以知道什么时候和谁更新了?

【问题讨论】:

  • 用你的代码编辑你的问题,对不起,我不明白你的问题
  • 已编辑 @alessandro 谢谢

标签: asp.net-core entity-framework-core


【解决方案1】:

创建新的基础模型类。每个模型必须至少有一个或多个相同的列,例如 ID、CreatedBy 等。然后将基本模型与所有模型链接。

BaseModel.cs

public class BaseModel
{
     public int ID { get; set; }
     public DateTime? Created { get; set; }
     public string CreatedBy { get; set; }
     public DateTime? LastModified { get; set; }
     public string LastModifiedBy { get; set; }
}

用户.cs

public class User : BaseModel 
{
     public string Name { get; set; }
     public int Age {get; set; }
}

YourDbContext.cs

public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
    {
        var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseModel && (x.State == EntityState.Added || x.State == EntityState.Modified));
        DateTime dt = DateTime.Now;

        foreach (var entity in entities)
        {
            if (entity.State == EntityState.Added)
            {
                ((BaseModel)entity.Entity).CreatedBy = _currentUserService.UserId;
                ((BaseModel)entity.Entity).Created = dt;
            }
            else if (entity.State == EntityState.Modified)
            {
                ((BaseModel)entity.Entity).ModifiedBy = _currentUserService.UserId;
                ((BaseModel)entity.Entity).LastModified = dt;
            }
        }
        return base.SaveChangesAsync(cancellationToken);
    }

【讨论】:

    猜你喜欢
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2010-12-21
    相关资源
    最近更新 更多