protected override bool ResolveConflicts(IEnumerable <DbEntityEntry> conflicts) { ObjectContext objectContext = ((IObjectContextAdapter)this.DbContext).ObjectContext; ObjectStateManager objectStateManager = objectContext.ObjectStateManager; foreach (DbEntityEntry entityEntry in conflicts) { ObjectStateEntry stateEntry = objectStateManager.GetObjectStateEntry(entityEntry.Entity); if (entityEntry.State == EntityState.Detached || stateEntry.IsRelationship) { continue; } Type entityType = stateEntry.Entity.GetType(); if (entityType == typeof(Product)) { if (!this.ResolveProductConflict(entityEntry)) { return(false); } } } return(true); }
private ObjectStateEntry GetEntityEntryFromRelation(ObjectStateEntry relationEntry, int index) { var firstKey = (EntityKey)relationEntry.OriginalValues[index]; ObjectStateEntry entry = ObjectStateManager.GetObjectStateEntry(firstKey); return(entry); }
/// <summary> /// Private extension method for ObjectStateManager class /// Dump all tracking info to a string /// </summary> /// <param name="manager">ObjectStateManager</param> /// <param name="objectStateEntries">Collection of ObjectStateEntries. If null, then all entities will be displayed</param> /// <param name="entityKey">EntityKey of given entity. If null, then all entities will be displayed</param> /// <param name="asHtml">Output string as HTML</param> /// <returns>String with tracking info about entries</returns> private static string Dump( ObjectStateManager manager, IEnumerable<ObjectStateEntry> objectStateEntries, EntityKey entityKey, bool asHtml) { StringBuilder dump = new StringBuilder(); if (entityKey != null) { objectStateEntries = new List<ObjectStateEntry>(); (objectStateEntries as List<ObjectStateEntry>).Add(manager.GetObjectStateEntry(entityKey)); } else if (objectStateEntries == null) { objectStateEntries = manager.GetObjectStateEntries(~EntityState.Detached); } dump.AppendFormat("ObjectStateManager entries : # {0}\n", objectStateEntries.Count()); foreach (var entry in objectStateEntries) { dump.Append(ObjectStateEntryToString(entry)); if (entry.State == EntityState.Added) { for (int i = 0; i < entry.CurrentValues.FieldCount; i++) { dump.AppendFormat("\n\t- {0} = {1}", entry.CurrentValues.GetName(i), ObjectToString(entry.CurrentValues[i])); } } else if (entry.State == EntityState.Modified) { foreach (string prop in entry.GetModifiedProperties()) { dump.AppendFormat("\n\t- {0} : {1} -> {2}", prop, ObjectToString(entry.OriginalValues[prop]), ObjectToString(entry.CurrentValues[prop])); } } } if (asHtml) { dump.Replace("\n", "<br />"); dump.Replace("\t", " "); } else { dump.Replace("<b>", ""); dump.Replace("</b>", ""); } return dump.ToString(); }
/// <summary> /// Private extension method for ObjectStateManager class /// Dump all tracking info to a string /// </summary> /// <param name="manager">ObjectStateManager</param> /// <param name="objectStateEntries">Collection of ObjectStateEntries. If null, then all entities will be displayed</param> /// <param name="entityKey">EntityKey of given entity. If null, then all entities will be displayed</param> /// <param name="asHtml">Output string as HTML</param> /// <returns>String with tracking info about entries</returns> private static string Dump( ObjectStateManager manager, IEnumerable <ObjectStateEntry> objectStateEntries, EntityKey entityKey, bool asHtml) { StringBuilder dump = new StringBuilder(); if (entityKey != null) { objectStateEntries = new List <ObjectStateEntry>(); (objectStateEntries as List <ObjectStateEntry>).Add(manager.GetObjectStateEntry(entityKey)); } else if (objectStateEntries == null) { objectStateEntries = manager.GetObjectStateEntries(~EntityState.Detached); } dump.AppendFormat("ObjectStateManager entries : # {0}\n", objectStateEntries.Count()); foreach (var entry in objectStateEntries) { dump.Append(ObjectStateEntryToString(entry)); if (entry.State == EntityState.Added) { for (int i = 0; i < entry.CurrentValues.FieldCount; i++) { dump.AppendFormat("\n\t- {0} = {1}", entry.CurrentValues.GetName(i), ObjectToString(entry.CurrentValues[i])); } } else if (entry.State == EntityState.Modified) { foreach (string prop in entry.GetModifiedProperties()) { dump.AppendFormat("\n\t- {0} : {1} -> {2}", prop, ObjectToString(entry.OriginalValues[prop]), ObjectToString(entry.CurrentValues[prop])); } } } if (asHtml) { dump.Replace("\n", "<br />"); dump.Replace("\t", " "); } else { dump.Replace("<b>", ""); dump.Replace("</b>", ""); } return(dump.ToString()); }
IEnumerable <ModifiedProperty> IAuditableContext.GetModifiedProperties(object entity) { ObjectStateEntry entry = ObjectStateManager.GetObjectStateEntry(entity); return (entry.GetModifiedProperties().Select( p => new ModifiedProperty(entity.GetType().GetProperty(p), entry.OriginalValues[p], entry.CurrentValues[p]))); }
public bool RefreshObject <TEntity>(TEntity entity) { var objectStateEntry = ObjectStateManager.GetObjectStateEntry(entity); // Refresh( RefreshMode.ClientWins, entity ); Refresh(RefreshMode.StoreWins, entity); if (objectStateEntry.State == EntityState.Detached || objectStateEntry.State == EntityState.Deleted) { return(false); } return(true); }
public override void OnBeforeDelete(DbContext dbContext, ObjectStateManager manager, IAuditTrail item) { var entry = manager.GetObjectStateEntry(item); var auditString = new StringBuilder(); auditString.AppendFormat("Entity Name {0} :DELETED: ", item.GetType()); foreach (var propName in entry.GetModifiedProperties()) { auditString.AppendFormat("{0}", propName); auditString.AppendFormat("=>{0}:", entry.OriginalValues[propName]); } _auditStrings.Add(auditString.ToString()); }
void OnSavingChanges(object sender, EventArgs e) { var modifiedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Modified); foreach (var entry in modifiedEntities) { var modifiedProps = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).GetModifiedProperties(); var currentValues = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).CurrentValues; foreach (var propName in modifiedProps) { var newValue = currentValues[propName]; //log changes } } }
/// <summary> /// откатить одну entity /// </summary> /// <param name="entity"></param> private void RevertEntityScalars(EntityObject entity) { ServerAction = true; var custEntry = ObjectStateManager.GetObjectStateEntry(entity.EntityKey); var dri = custEntry.CurrentValues.DataRecordInfo; for (var i = 0; i < custEntry.CurrentValues.FieldCount; i++) { var propName = dri.FieldMetadata[i].FieldType.Name; if (!(from keys in custEntry.EntityKey.EntityKeyValues where keys.Key == propName select keys).Any()) { custEntry.CurrentValues.SetValue(i, custEntry.OriginalValues[i]); } } ServerAction = false; }
public override void OnAfterInsert(DbContext dbContext, ObjectStateManager manager, IAuditTrail item) { var entry = manager.GetObjectStateEntry(item); var auditString = new StringBuilder(); auditString.AppendFormat("Entity Name {0} :INSERTED: ", item.GetType()); foreach (var prop in item.GetType().GetProperties()) { try { var val = entry.OriginalValues[prop.Name]; auditString.AppendFormat("{0}", prop.Name); auditString.AppendFormat("=>{0}:", val); } catch (ArgumentOutOfRangeException) { } } _auditStrings.Add(auditString.ToString()); }
public string GetChanges(object myObject) { string res = ""; if (ObjectStateManager != null) { var myObjectState = ObjectStateManager.GetObjectStateEntry(myObject); if (myObjectState != null) { var modifiedProperties = myObjectState.GetModifiedProperties(); if (modifiedProperties != null) { foreach (var propName in modifiedProperties) { res += String.Format("Property {0} changed from {1} to {2}", propName, myObjectState.OriginalValues[propName], myObjectState.CurrentValues[propName]); } } } } return(res); }
/// <summary> /// Updates each entry in the ChangeSet with its corresponding conflict info. /// </summary> /// <param name="operationConflictMap">Map of conflicts to their corresponding operations entries.</param> private void SetChangeSetConflicts(Dictionary <DbEntityEntry, ChangeSetEntry> operationConflictMap) { object storeValue; EntityKey refreshEntityKey; ObjectContext objectContext = ((IObjectContextAdapter)DbContext).ObjectContext; ObjectStateManager objectStateManager = objectContext.ObjectStateManager; if (objectStateManager == null) { throw Error.InvalidOperation(Resource.ObjectStateManagerNotFoundException, DbContext.GetType().Name); } foreach (var conflictEntry in operationConflictMap) { DbEntityEntry entityEntry = conflictEntry.Key; ObjectStateEntry stateEntry = objectStateManager.GetObjectStateEntry(entityEntry.Entity); if (stateEntry.State == EntityState.Unchanged) { continue; } // Note: we cannot call Refresh StoreWins since this will overwrite Current entity and remove the optimistic concurrency ex. ChangeSetEntry operationInConflict = conflictEntry.Value; refreshEntityKey = RefreshContext.CreateEntityKey(stateEntry.EntitySet.Name, stateEntry.Entity); RefreshContext.TryGetObjectByKey(refreshEntityKey, out storeValue); operationInConflict.StoreEntity = storeValue; // StoreEntity will be null if the entity has been deleted in the store (i.e. Delete/Delete conflict) bool isDeleted = (operationInConflict.StoreEntity == null); if (isDeleted) { operationInConflict.IsDeleteConflict = true; } else { // Determine which members are in conflict by comparing original values to the current DB values PropertyDescriptorCollection propDescriptors = TypeDescriptor.GetProperties(operationInConflict.Entity.GetType()); List <string> membersInConflict = new List <string>(); object originalValue; PropertyDescriptor pd; for (int i = 0; i < stateEntry.OriginalValues.FieldCount; i++) { originalValue = stateEntry.OriginalValues.GetValue(i); if (originalValue is DBNull) { originalValue = null; } string propertyName = stateEntry.OriginalValues.GetName(i); pd = propDescriptors[propertyName]; if (pd == null) { // This might happen in the case of a private model // member that isn't mapped continue; } if (!Object.Equals(originalValue, pd.GetValue(operationInConflict.StoreEntity))) { membersInConflict.Add(pd.Name); } } operationInConflict.ConflictMembers = membersInConflict; } } }
public static List <CustomLog> GetLogEntries(ObjectStateManager entities) { List <CustomLog> listLogs = new List <CustomLog>(); var entries = entities.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted); var user = HttpContext.Current.User.Identity.Name; foreach (var entry in entries) { var tableName = entry.Entity.GetType().Name; if (tableName.Contains("SAX_PARTIDAS")) { return(new List <CustomLog>()); } var pk = GetPrimaryKeys(entry); if (entry.State == EntityState.Added) { var newgroup = Guid.NewGuid(); var currentEntry = entities.GetObjectStateEntry(entry.EntityKey); var currentValues = currentEntry.CurrentValues; for (var i = 0; i < currentValues.FieldCount; i++) { var propName = currentValues.DataRecordInfo.FieldMetadata[i].FieldType.Name; var newValue = currentValues[propName].ToString(); var log = new CustomLog() { Id = Guid.NewGuid(), GuidGroup = newgroup, Action = "I", TableName = tableName, PrimaryKey = pk, ColumnName = propName, OldValue = null, NewValue = newValue, Date = DateTime.Now, UserId = user }; listLogs.Add(log); } } else if (entry.State == EntityState.Modified) { var currentEntry = entities.GetObjectStateEntry(entry.EntityKey); var currentValues = currentEntry.CurrentValues; var originalValues = currentEntry.OriginalValues; var properties = currentEntry.GetModifiedProperties(); var updgroup = Guid.NewGuid(); foreach (var propName in properties) { var oldValue = originalValues[propName].ToString(); var newValue = currentValues[propName].ToString(); if (oldValue == newValue) { continue; } var log = new CustomLog() { Id = Guid.NewGuid(), GuidGroup = updgroup, Action = "M", TableName = tableName, PrimaryKey = pk, ColumnName = propName, OldValue = oldValue, NewValue = newValue, Date = DateTime.Now, UserId = user }; listLogs.Add(log); } } else if (entry.State == EntityState.Deleted) { var currentEntry = entities.GetObjectStateEntry(entry.EntityKey); var originalValues = currentEntry.OriginalValues; var delgroup = Guid.NewGuid(); for (var i = 0; i < originalValues.FieldCount; i++) { var oldValue = originalValues[i].ToString(); var log = new CustomLog() { Id = Guid.NewGuid(), GuidGroup = delgroup, Action = "D", TableName = tableName, PrimaryKey = pk, ColumnName = null, OldValue = oldValue, NewValue = null, Date = DateTime.Now, UserId = user }; listLogs.Add(log); } } } return(listLogs); }
public bool IsObjectAttached <TEntity>(TEntity objectToCheck) { var objectStateEntry = ObjectStateManager.GetObjectStateEntry(objectToCheck); return(objectStateEntry.State != EntityState.Detached); }
private string GetPrimaryKey(DbEntityEntry entry) { var objectStateEntry = _objectStateManager.GetObjectStateEntry(entry.Entity); return(String.Join("_", objectStateEntry.EntityKey.EntityKeyValues.Select(x => x.Value))); }
private bool ShouldAuditProperty(PropertyInfo property, object entity) { var stateEntry = ObjectStateManager.GetObjectStateEntry(entity); return(!stateEntry.IsRelationship); }