public void AddDataLog(DataChangeLog log) { using (var c = new MongoDbRepository <DataChangeLog>(DBName)) { c.Add(log); } }
public DataChangeLog GetChangeLogs() { DataChangeLog dlog = new DataChangeLog(); var changedProps = _tracker.GetChanges(this); foreach (var trackingMember in changedProps) { var log = new ValueLog(); log.Name = trackingMember.name; log.OldValue = _oldValues.ContainsKey(log.Name) ? _oldValues[log.Name] : null; log.NewValue = trackingMember.value; dlog.Add(log); } return(dlog); }
/// <summary> /// 获取数据变更记录 /// </summary> /// <param name="context">数据上下文</param> /// <param name="entity">更改后的数据实体,这个数据实体应该是从数据库里读取出来的才有效</param> /// <param name="containsIdProp">是否包含外键Id字段</param> /// <returns></returns> public static DataChangeLog GetChangeLog(this DbContext context, object entity, bool containsIdProp = true) { // 记录变更轨迹 var entry = context.Entry(entity); var stateEntry = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity); var currentValues = stateEntry.CurrentValues; var originalValues = stateEntry.OriginalValues; //var modifiedProperties = stateEntry.GetModifiedProperties(); var modifiedProperties = entry.CurrentValues.PropertyNames.Where(propertyName => entry.Property(propertyName).IsModified) .ToList(); var changelog = new DataChangeLog { DateTime = DateTime.Now, Name = entity.GetTypeDisplayName(), Type = entity.GetTypeFullName() }; foreach (var prop in modifiedProperties) { var currentValue = currentValues.GetValue(currentValues.GetOrdinal(prop)); var originalValue = originalValues.GetValue(originalValues.GetOrdinal(prop)); if (!originalValue.Equals(currentValue)) // 值已经改变的 { // 判断是否包含 ID 属性 if (containsIdProp || !prop.ToLower().EndsWith("id")) { changelog.DataChangeLogItems.Add(new DataChangeLogItem { Name = entity.GetType().GetPropertyDisplayName(prop), CurrentValue = currentValue, OriginalValue = originalValue }); } } } return(changelog); }