• EF记录统一添加创建,修改时间


    public class BaseEntity
    {
        public DateTime? DateCreated { get; set; }
        public string UserCreated { get; set; }
        public DateTime? DateModified { get; set; }
        public string UserModified { get; set; }
    }

    We’ll add the DateCreatedUserCreatedDateModified and UserModified fields to each entity by creating a BaseEntity.cs class. Each entity that you want to contain these fields should inherit this class.

    For example, my Student.cs entity will looks like this:

    public class Student : BaseEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    In this step we’ll intercept entites as they are saved and update their created and modified fields automtically. Take a look at my DbContext below:

    public class SchoolContext : DbContext
    {
        public DbSet<Student> Students { get; set; }
    
        public override int SaveChanges()
        {
            AddTimestamps();
            return base.SaveChanges();
        }
     
        public override async Task<int> SaveChangesAsync()
        {
            AddTimestamps();
            return await base.SaveChangesAsync();
        }
    
        private void AddTimestamps()
        {
            var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));
    
            var currentUsername = !string.IsNullOrEmpty(System.Web.HttpContext.Current?.User?.Identity?.Name)
                ? HttpContext.Current.User.Identity.Name
                : "Anonymous";
    
            foreach (var entity in entities)
            {
                if (entity.State == EntityState.Added)
                {
                    ((BaseEntity)entity.Entity).DateCreated = DateTime.UtcNow;
                    ((BaseEntity)entity.Entity).UserCreated = currentUsername;
                }
    
                ((BaseEntity)entity.Entity).DateModified = DateTime.UtcNow;
                ((BaseEntity)entity.Entity).UserModified = currentUsername;
            }
        }
    }
  • 相关阅读:
    TCP/IP详解学习笔记
    C++知识库
    C++中基类的析构函数为什么要用virtual虚析构函数
    秒杀多线程面试题系列
    很详细全部的WinDbg学习资料
    Ubuntu中libprotobuf版本冲突的解决方案
    Windows系统中内存泄露与检测工具及方法
    Ubuntu脚本修改IP信息
    【Qt】Qt Quick 之 QML 与 C++ 混合编程详解
    分布式系统消息中间件——RabbitMQ的使用基础篇
  • 原文地址:https://www.cnblogs.com/luhe/p/9259792.html
Copyright © 2020-2023  润新知