摘自:https://www.cnblogs.com/tdfblog/p/entity-framework-core-generate-tracking-columns.html Ef Core 官方文檔: https://docs.microsoft.com/zh-cn/ef/core/ 文章列舉 ...
摘自:https://www.cnblogs.com/tdfblog/p/entity-framework-core-generate-tracking-columns.html
Ef Core 官方文檔: https://docs.microsoft.com/zh-cn/ef/core/
文章列舉了三種:讀寫屬性、只讀屬性、不定義屬性(陰影屬性 Shadow )。
下麵是摘的一種陰影屬性簡單實現:
一、添加陰影屬性:
1. 在 OnModelCreating 方法中聲明陰影屬性:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.AddAuditableShadowProperties(); base.OnModelCreating(modelBuilder); }
2. 這裡是 AddAuditableShadowProperties 實現:
public static readonly string CreatedByUserId = nameof(CreatedByUserId); public static readonly string ModifiedByUserId = nameof(ModifiedByUserId); public static readonly string CreatedDateTime = nameof(CreatedDateTime); public static readonly string ModifiedDateTime = nameof(ModifiedDateTime); public static void AddAuditableShadowProperties(this ModelBuilder modelBuilder) { var models = modelBuilder.Model .GetEntityTypes() .Where(e => typeof(IEntityBase).IsAssignableFrom(e.ClrType)); foreach (var entityType in models) { modelBuilder.Entity(entityType.ClrType) .Property<long?>(CreatedByUserId); modelBuilder.Entity(entityType.ClrType) .Property<long?>(ModifiedByUserId); modelBuilder.Entity(entityType.ClrType) .Property<DateTimeOffset?>(CreatedDateTime); modelBuilder.Entity(entityType.ClrType) .Property<DateTimeOffset?>(ModifiedDateTime); } }
二、修改陰影屬性:
1. 重寫 SaveChange 方法:
public override int SaveChanges() { ChangeTracker.DetectChanges(); //保存之前修改陰影屬性 SetShadowProperties(); // for performance reasons, to avoid calling DetectChanges() again. ChangeTracker.AutoDetectChangesEnabled = false; var result = base.SaveChanges(); ChangeTracker.AutoDetectChangesEnabled = true; return result; } private void SetShadowProperties() { // we can't use constructor injection anymore, because we are using the `AddDbContextPool<>` var httpContextAccessor = this.GetService<IHttpContextAccessor>(); ChangeTracker.SetAuditableEntityPropertyValues(httpContextAccessor); }
2. 修改陰影屬性:
public static void SetAuditableEntityPropertyValues(this ChangeTracker changeTracker, IHttpContextAccessor httpContextAccessor) { var httpContext = httpContextAccessor?.HttpContext; // var userAgent = httpContext?.Request?.Headers["User-Agent"].ToString(); // var userIp = httpContext?.Connection?.RemoteIpAddress?.ToString(); var now = DateTimeOffset.Now; var modifiedEntries = changeTracker.Entries<IEntityBase>().Where(x => x.State == EntityState.Modified); foreach (var modifiedEntry in modifiedEntries) { modifiedEntry.Property(ModifiedDateTime).CurrentValue = now; modifiedEntry.Property(ModifiedByUserId).CurrentValue = 953833173853548544; } var addedEntries = changeTracker.Entries<IEntityBase>().Where(x => x.State == EntityState.Added); foreach (var addedEntry in addedEntries) { addedEntry.Property(CreatedDateTime).CurrentValue = now; addedEntry.Property(CreatedByUserId).CurrentValue = 953833173853548544; } }