c# - 实体框架:从迁移更改中排除审计属性
问题描述
我有一个由实体框架驱动的数据访问层的解决方案。一切正常,大约有 57 个实体。每个实体都继承自 EntityBase 类,该类包含仅在记录发生更改时才更新的审计字段。但是,由于某种原因,当我执行迁移时,我的记录似乎已被修改,这会更新实体审计字段,并使我的迁移过程每次需要 24 分钟才能运行。一张表种子数据并有 115000 行,每次运行“更新”。
实体库:
public abstract class EntityBase
{
[Required]
[MaxLength(200)]
public string CreatedBy { get; set; }
[Required]
public DateTime DateCreated { get; set; }
[MaxLength(200)]
public string UpdatedBy { get; set; }
public DateTime? DateUpdated { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
如何在 Context 类中更新审计字段:
public override int SaveChanges()
{
try
{
SetAudit();
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
var sb = new StringBuilder();
foreach (var failure in ex.EntityValidationErrors)
{
sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
{
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
sb.AppendLine();
}
}
throw new DbEntityValidationException("Entity Validation Failed - errors follow:\n" + sb, ex); // Add the original exception as the innerException
}
catch (Exception ex)
{
throw ex;
}
}
private void SetAudit()
{
var addedAuditedEntities = ChangeTracker.Entries<EntityBase>().Where(p => p.State == EntityState.Added)
.Select(p => p.Entity);
var modifiedAuditedEntities = ChangeTracker.Entries<EntityBase>().Where(p => p.State == EntityState.Modified)
.Select(p => p.Entity);
var now = DateTime.UtcNow;
foreach (var added in addedAuditedEntities)
{
added.DateCreated = now;
added.CreatedBy = OwinContextHelper.CurrentApplicationUser;
added.DateUpdated = now;
added.UpdatedBy = OwinContextHelper.CurrentApplicationUser;
}
foreach (var modified in modifiedAuditedEntities)
{
if (modified.DateCreated == DateTime.MinValue)
modified.DateCreated = now;
if (string.IsNullOrEmpty(modified.CreatedBy))
modified.CreatedBy = OwinContextHelper.CurrentApplicationUser;
modified.DateUpdated = now;
modified.UpdatedBy = OwinContextHelper.CurrentApplicationUser;
}
}
我如何从迁移中排除我的审计字段,因为它是'RowVersion'可能会改变?