先上一段最近項目中的代碼,此代碼可以放到自己項目中的dbContext中 EF6中可以覆寫SaveChangesAsync(非同步)或者SaveChanges來實現記錄變化的跟蹤,這其中包括新增、修改、和刪除,dbContext中的屬性ChangeTracker可以跟蹤屬性的變化,即查找實體修改記錄: ...
先上一段最近項目中的代碼,此代碼可以放到自己項目中的dbContext中
public override Task<int> SaveChangesAsync() { List<AuditLog> AuditLogs = new List<AuditLog>(); List<DataLensTrackingLog> trackinglogs = new List<DataLensTrackingLog>(); var changeTracker = ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified); try { foreach (var entity in changeTracker) { AuditLogs.Clear(); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement(TrackingLog.Records)); if (entity.Entity != null) { var entityName = ObjectContext.GetObjectType(entity.Entity.GetType()).Name; //string entityName = entity.Entity.GetType().Name; EntityState state = entity.State; switch (entity.State) { case EntityState.Modified: //entityName = ObjectContext.GetObjectType(entity.Entity.GetType()).Name; foreach (string prop in entity.OriginalValues.PropertyNames) { object currentValue = entity.CurrentValues[prop]; object originalValue = entity.GetDatabaseValues()[prop];//OriginalValues[prop]; if (!Object.Equals(currentValue, originalValue)&&entity.Property(prop).IsModified==true &&prop.ToLower()!="lastupdateby") { AuditLogs.Add(new AuditLog { EntityName = entityName, RecordID = PrimaryKeyValue(entity), State = state, ColumnName = prop, OriginalValue = Convert.ToString(originalValue), NewValue = Convert.ToString(currentValue), }); } } if (AuditLogs.Count > 0) { TrackingLog.GetXmlForUpdate(doc, AuditLogs); trackinglogs.Add(new DataLensTrackingLog { EntityName = entityName, Email = this.Email, XmlDoc = CompressionHelper.Compresse("XmlDoc", new UTF8Encoding().GetBytes(doc.OuterXml)), CreateTime = DateTime.Now }); } break; case EntityState.Added: //entityName = ObjectContext.GetObjectType(entity.Entity.GetType()).Name; foreach (string prop in entity.CurrentValues.PropertyNames) { AuditLogs.Add(new AuditLog { EntityName = entityName, RecordID = PrimaryKeyValue(entity), State = state, ColumnName = prop, OriginalValue = string.Empty, NewValue = entity.CurrentValues[prop], }); } TrackingLog.GetXmlForUpdate(doc, AuditLogs); trackinglogs.Add(new DataLensTrackingLog { EntityName = entityName, Email = this.Email, XmlDoc = CompressionHelper.Compresse("XmlDoc", new UTF8Encoding().GetBytes(doc.OuterXml)), CreateTime = DateTime.Now }); break; case EntityState.Deleted: //entityName = ObjectContext.GetObjectType(entity.Entity.GetType()).Name; foreach (string prop in entity.OriginalValues.PropertyNames) { AuditLogs.Add(new AuditLog { EntityName = entityName, RecordID = PrimaryKeyValue(entity), State = state, ColumnName = prop, OriginalValue = entity.OriginalValues[prop], NewValue = string.Empty, }); } TrackingLog.GetXmlForUpdate(doc, AuditLogs); trackinglogs.Add(new DataLensTrackingLog { EntityName = entityName, Email = this.Email, XmlDoc = CompressionHelper.Compresse("XmlDoc", new UTF8Encoding().GetBytes(doc.OuterXml)), CreateTime = DateTime.Now }); break; default: break; } } } DataTable dt=TypeConvert.ToDataTable(trackinglogs); SqlDataHelper.SqlBulkCopy(dt, "DataLensTrackingLog", DataBaseType.ConnLogDataStr); return base.SaveChangesAsync(); } catch (Exception ex) { throw ex; } }
EF6中可以覆寫SaveChangesAsync(非同步)或者SaveChanges來實現記錄變化的跟蹤,這其中包括新增、修改、和刪除,
dbContext中的屬性ChangeTracker可以跟蹤屬性的變化,即查找實體修改記錄:ChangeTracker.Entries().Where(p => p.State ==EntityState.Modified);
查找新增的實體記錄行:ChangeTracker.Entries().Where(p => p.State == EntityState.Added);查找刪除的實體記錄行:
ChangeTracker.Entries().Where(p => p.State == EntityState.Deleted)
獲取實體的名字是ObjectContext.GetObjectType(entity.Entity.GetType()).Name,之前獲取實體是通過以下方式:
entity.Entity.GetType().Name,但是這種方式會有一個問題,假如說存在以下實體
public partial class DataLensDataPointUniverse { [Key] public int DataPointUniverseId { get; set; } public int DomicileId { get; set; } public int ShareClassUniverseId { get; set; } public int DataPointId { get; set; } public int CollectionStatusId { get; set; } public Nullable<System.DateTime> CollectionStartDate { get; set; } public Nullable<System.DateTime> CollectionEndDate { get; set; } public int CollectionFrequencyId { get; set; } public int CollectionPriorityId { get; set; } public string Restrictions { get; set; } public int FundFormId { get; set; } public string InterpretationRules { get; set; } public string Comments { get; set; } public string QualityMeasureCompleteness { get; set; } public string QualityMeasureTimeliness { get; set; } public string QualityMeasureAccuracy { get; set; } public int FundCollectionRequirementId { get; set; } public int LEANProjectId { get; set; } public Nullable<System.Guid> CreateBy { get; set; } public Nullable<System.Guid> LastUpdateBy { get; set; } public Nullable<System.DateTime> CreateDate { get; set; } public Nullable<System.DateTime> LastUpdateDate { get; set; } public virtual DataLensDataPoint DataLensDataPoint { get; set; } }
這時候獲取的實體名字就可能是類似於這種格式343434343_DataLensDataPoint_3434,為什麼會存在這種格式呢,因為該實體中的DataPointId是另個屬性 public virtual DataLensDataPoint DataLensDataPoint { get; set; }中的外鍵,即(即實體DataLensDataPoint中DataPointId)
獲取屬性當前值entity.CurrentValues[prop](即還未保存到資料庫),獲取資料庫當前值entity.GetDatabaseValues()[prop]
其中的entity.Property(prop).IsModified==true屬性是來判斷確實該值要存到資料庫中,才要去記錄日誌,因為在Save
之前可能有些實體屬性被標記為不做更改entity.Property(prop).IsModified==false;
獲取實體主鍵的值可以用以下方法
private string PrimaryKeyValue(DbEntityEntry entry) { var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity); if (null == objectStateEntry.EntityKey.EntityKeyValues) { return string.Empty; } return string.Join(",", objectStateEntry.EntityKey.EntityKeyValues.Select(item => item.Value.ToString()).ToArray()); }