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;
            }
        }
    }
  • 相关阅读:
    学生管理系统
    python集合(方法)
    python字典(包括方法)
    python元组(包括方法)
    python列表(包含列表方法)
    python索引
    python三元运算
    python while循环
    python-if语句
    python数据类型和运算符
  • 原文地址:https://www.cnblogs.com/luhe/p/9259792.html
Copyright © 2011-2022 走看看