zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    }
  • 相关阅读:
    蓝牙打印机的连接方法
    CE不能开机的可能情况
    手机性能指标的建议
    WINCE中使用键盘钩子的注意事项
    Wave接口开发注意事项
    解决唤醒屏不亮的问题之总结
    WM系统有用的注册表(研发人员使用)
    快速求解两个时间之间的天数
    测试SqlBulkCopy类批量插入数据
    Xml与DataTable相互转换方法
  • 原文地址:https://www.cnblogs.com/luhe/p/9259792.html
Copyright © 2011-2022 走看看