先上一段最近项目中的代码,此代码可以放到自己项目中的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()); }
当我们进行数据批量修改的时候我们可以用到EntityFramework.Extended,而不至于一条条的去更新数据库,增添了与数据库的I/O次数,具体的github地址地址为:
https://github.com/loresoft/EntityFramework.Extended,但是同时会有个问题,我们就没法做entitiframework的tracking log的使用,即使用SaveChanges的时候捕捉不到任何变化,如果想使用批量,又能捕捉到变化,可以使用entitiframework来执行sql语句来批量更新,并且也能捕获到数据改变的情况,因为使用了SaveChanges(),参考链接为:/wujingtao/p/5412329.html
Note:EntityFramework.Extended也支持事务.
原文:http://www.jianzhaoyang.com/cby-love/p/5746654.html