private static void Method08() { Member member = new Member { Id = 1, Password = "******" + DateTime.Now.Second }; using (var db = new DataContext()) { //先查询一次,让上下文中存在相同主键的对象 Member oldMember = db.Members.Single(m => m.Id == 1); Console.WriteLine("更新前:{0}。", oldMember.AddDate); try { DbEntityEntry <Member> entry = db.Entry(member); entry.State = EntityState.Unchanged; entry.Property("Password").IsModified = true; } catch (InvalidOperationException) { ObjectContext objectContext = ((IObjectContextAdapter)db).ObjectContext; ObjectStateEntry objectEntry = objectContext.ObjectStateManager.GetObjectStateEntry(oldMember); objectEntry.ApplyCurrentValues(member); objectEntry.ChangeState(EntityState.Unchanged); objectEntry.SetModifiedProperty("Password"); } db.Configuration.ValidateOnSaveEnabled = false; int count = db.SaveChanges(); db.Configuration.ValidateOnSaveEnabled = true; Console.WriteLine("操作结果:{0}", count > 0 ? "更新成功。" : "未更新。"); Member newMember = db.Members.Single(m => m.Id == 1); Console.WriteLine("更新后:{0}。", newMember.Password); } }
/// <summary> /// 更新指定字段 /// </summary> /// <param name="item">实体对象</param> /// <param name="paramField">字段</param> public void UpdateField(TEntity item, params string[] paramField) { using (DBContext <TEntity> context = new DBContext <TEntity>()) { try { ObjectContext dbcontext = ((IObjectContextAdapter)context).ObjectContext; context.Set <TEntity>().Attach(item); ObjectStateEntry stateEntry = dbcontext.ObjectStateManager.GetObjectStateEntry(item); foreach (string field in paramField) { stateEntry.SetModifiedProperty(field); } stateEntry.SetModified(); dbcontext.SaveChanges(); } catch (DbEntityValidationException ex) { throw ex; } } }
public static ObjectStateEntry AttachAsModifiedInternal <TEntity>(TEntity current, TEntity original, ObjectContext objectContext) { ObjectStateEntry stateEntry = objectContext.ObjectStateManager.GetObjectStateEntry(current); stateEntry.ApplyOriginalValues(original); // For any members that don't have RoundtripOriginal applied, EF can't determine modification // state by doing value comparisons. To avoid losing updates in these cases, we must explicitly // mark such members as modified. PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(TEntity)); AttributeCollection attributes = TypeDescriptor.GetAttributes(typeof(TEntity)); bool isRoundtripType = attributes[typeof(RoundtripOriginalAttribute)] != null; foreach (var fieldMetadata in stateEntry.CurrentValues.DataRecordInfo.FieldMetadata) { string memberName = stateEntry.CurrentValues.GetName(fieldMetadata.Ordinal); PropertyDescriptor property = properties[memberName]; // TODO: below we need to replace ExcludeAttribute logic with corresponding // DataContractMember/IgnoreDataMember logic if (property != null && (property.Attributes[typeof(RoundtripOriginalAttribute)] == null && !isRoundtripType) /* && property.Attributes[typeof(ExcludeAttribute)] == null */) { stateEntry.SetModifiedProperty(memberName); } } return(stateEntry); }
public static ObjectStateEntry AttachAsModifiedInternal(object current, object original, ObjectContext objectContext) { ObjectStateEntry stateEntry = objectContext.ObjectStateManager.GetObjectStateEntry(current); stateEntry.ApplyOriginalValues(original); // For any members that don't have RoundtripOriginal applied, EF can't determine modification // state by doing value comparisons. To avoid losing updates in these cases, we must explicitly // mark such members as modified. Type entityType = current.GetType(); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); AttributeCollection attributes = TypeDescriptor.GetAttributes(entityType); bool isRoundtripType = attributes[typeof(RoundtripOriginalAttribute)] != null; foreach (var fieldMetadata in stateEntry.CurrentValues.DataRecordInfo.FieldMetadata) { string memberName = stateEntry.CurrentValues.GetName(fieldMetadata.Ordinal); PropertyDescriptor property = properties[memberName]; if (property != null && (property.Attributes[typeof(RoundtripOriginalAttribute)] == null && !isRoundtripType) && property.Attributes[typeof(ExcludeAttribute)] == null) { stateEntry.SetModifiedProperty(memberName); } } return(stateEntry); }
/// <summary> /// Goes through an ObjectStateEntry and sets every property other /// than the key properties to be modified. /// </summary> /// <param name="entry"></param> static void SetEntryModified(ObjectContext context, object item) { ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(item); // One way of doing it, almost certainly others... for (int i = 0; i < entry.CurrentValues.FieldCount; i++) { bool isKey = false; string name = entry.CurrentValues.GetName(i); foreach (var keyPair in entry.EntityKey.EntityKeyValues) { if (string.Compare(name, keyPair.Key, true) == 0) { isKey = true; break; } } if (!isKey) { entry.SetModifiedProperty(name); } } }
public void AttachTask(Task task) { this.Tasks.Attach(task); ObjectStateEntry entry = this.ObjectStateManager.GetObjectStateEntry(task); foreach (string propertyName in task.GetModifiedProperties()) { entry.SetModifiedProperty(propertyName); } }
private static void UpdateOriginalValues(ObjectStateEntry entry, EntityInfo entityInfo) { var originalValuesMap = entityInfo.OriginalValuesMap; if (originalValuesMap == null || originalValuesMap.Keys.Count == 0) { return; } var originalValuesRecord = entry.GetUpdatableOriginalValues(); originalValuesMap.ToList().ForEach(kvp => { var propertyName = kvp.Key; var originalValue = kvp.Value; try { entry.SetModifiedProperty(propertyName); if (originalValue is JObject) { // only really need to perform updating original values on key properties // and a complex object cannot be a key. } else { var ordinal = originalValuesRecord.GetOrdinal(propertyName); var fieldType = originalValuesRecord.GetFieldType(ordinal); var originalValueConverted = ConvertValue(originalValue, fieldType); if (originalValueConverted == null) { // bug - hack because of bug in EF - see // http://social.msdn.microsoft.com/Forums/nl/adodotnetentityframework/thread/cba1c425-bf82-4182-8dfb-f8da0572e5da var temp = entry.CurrentValues[ordinal]; entry.CurrentValues.SetDBNull(ordinal); entry.ApplyOriginalValues(entry.Entity); entry.CurrentValues.SetValue(ordinal, temp); } else { originalValuesRecord.SetValue(ordinal, originalValueConverted); } } } catch (Exception e) { if (e.Message.Contains(" part of the entity's key")) { throw; } else { // this can happen for "custom" data entity properties. } } }); }
/// <summary> /// Marks all the scalar properties of the entity as modified on the specified /// <see cref="ObjectContext"/>. /// </summary> /// <remarks> /// This method is thread-safe. /// </remarks> /// <typeparam name="TEntity">The type of the entity</typeparam> /// <param name="entity">The entity</param> /// <param name="context">The <see cref="ObjectContext"/> that the entity is attached to</param> public static void SetAllModified <TEntity>(this TEntity entity, ObjectContext context) where TEntity : IEntityWithKey { ObjectStateEntry stateEntry = context.ObjectStateManager.GetObjectStateEntry(entity.EntityKey); IEnumerable <string> propertyNameList = stateEntry.CurrentValues.DataRecordInfo.FieldMetadata.Select(pn => pn.FieldType.Name); foreach (string propName in propertyNameList) { stateEntry.SetModifiedProperty(propName); } }
public static ObjectStateEntry SetModifiedProperty <T>(this ObjectStateEntry entry, Expression <Func <T, object> > expression) { var body = expression.Body as MemberExpression; if (body == null) { throw new ArgumentException("Parameter expr must be a memberexpression"); } entry.SetModifiedProperty(body.Member.Name); return(entry); }
public void Update(T entity, params string[] nameOfPropertyToUpdate) { entity.CheckNotNull("entity"); if (context.Entry <T>(entity).State == EntityState.Detached) { context.Set <T>().Attach(entity); } var createTimeProperty = context.Entry <T>(entity).Property("CreateTime"); if (createTimeProperty != null) { createTimeProperty.IsModified = false; } var createUserIDProperty = context.Entry <T>(entity).Property("CreateUserID"); if (createUserIDProperty != null) { createUserIDProperty.IsModified = false; } var createUserNameProperty = context.Entry <T>(entity).Property("CreateUserName"); if (createUserNameProperty != null) { createUserNameProperty.IsModified = false; } var modifyProperty = context.Entry <T>(entity).Property("ModifyTime"); if (modifyProperty != null) { modifyProperty.CurrentValue = DateTime.Now; } IObjectContextAdapter objectContextAdapter = context; ObjectContext objectContext = objectContextAdapter.ObjectContext; ObjectStateEntry ose = objectContext.ObjectStateManager.GetObjectStateEntry(entity); foreach (var p in nameOfPropertyToUpdate) { ose.SetModifiedProperty(p); } if (context.Entry <T>(entity).State == EntityState.Unchanged) { context.Entry <T>(entity).State = EntityState.Modified; } }
private void Merge_Click(object sender, EventArgs e) { ApplyChanges = true; object version = _entry.OriginalValues["Version"]; _entry.ChangeState(EntityState.Unchanged); _entry.GetUpdatableOriginalValues().SetValue(_entry.OriginalValues.GetOrdinal("Version"), version); foreach (TreeNode node in tree.Nodes) { if (node.Checked) { _entry.SetModifiedProperty(node.Tag.ToString()); } } Close(); }
//场景三的异常处理,从ObjectContext着手处理 public void Method8() { const string userName = "******"; long id; using (var db = new DefaultDbContext()) { id = db.Set <SysUser>().Single(m => m.UserName == userName).Id; } SysUser user = new SysUser { Id = id, Password = "******" + DateTime.Now.Second }; using (var db = new DefaultDbContext()) { //关闭自动跟踪,方便调试查看 db.Configuration.AutoDetectChangesEnabled = false; //通过查询,让上下文中存在相同主键的对象 SysUser oldUser = db.Set <SysUser>().Find(user.Id); System.Console.WriteLine("更新前:{0}。", oldUser.Password); try { DbEntityEntry <SysUser> entry = db.Entry(user); entry.State = EntityState.Unchanged; entry.Property("Password").IsModified = true; } catch (InvalidOperationException) { ObjectContext objectContext = ((IObjectContextAdapter)db).ObjectContext; ObjectStateEntry objectEntry = objectContext.ObjectStateManager.GetObjectStateEntry(oldUser); objectEntry.ApplyCurrentValues(user); objectEntry.ChangeState(EntityState.Unchanged); objectEntry.SetModifiedProperty("Password"); } db.Configuration.ValidateOnSaveEnabled = false; int count = db.SaveChanges(); db.Configuration.ValidateOnSaveEnabled = true; System.Console.WriteLine("操作结果:{0}", count > 0 ? "更新成功。" : "未更新。"); SysUser newUser = db.Set <SysUser>().Single(m => m.Id == id); System.Console.WriteLine("更新后:{0}。", newUser.Password); } }
public void UpdateEntityFields(T entity, List <string> fileds, bool isSave = true) { if ((object)entity == null || fileds == null || fileds.Count <= 0) { return; } this._db.Set <T>().Attach(entity); ObjectStateEntry objectStateEntry = ((IObjectContextAdapter)this._db).ObjectContext.ObjectStateManager.GetObjectStateEntry((object)entity); foreach (string filed in fileds) { objectStateEntry.SetModifiedProperty(filed); } if (!isSave) { return; } this.SaveChanges(); }
private static void UpdateOriginalValues(ObjectStateEntry entry, EntityInfo entityInfo) { var originalValuesMap = entityInfo.OriginalValuesMap; if (originalValuesMap == null || originalValuesMap.Keys.Count == 0) { return; } var originalValuesRecord = entry.GetUpdatableOriginalValues(); originalValuesMap.ToList().ForEach(kvp => { var propertyName = kvp.Key; var originalValue = kvp.Value; try { entry.SetModifiedProperty(propertyName); if (originalValue is JObject) { // only really need to perform updating original values on key properties // and a complex object cannot be a key. } else { var ordinal = originalValuesRecord.GetOrdinal(propertyName); var fieldType = originalValuesRecord.GetFieldType(ordinal); var originalValueConverted = ConvertValue(originalValue, fieldType); originalValuesRecord.SetValue(ordinal, originalValueConverted); } } catch (Exception e) { if (e.Message.Contains(" part of the entity's key")) { throw; } else { // this can happen for "custom" data entity properties. } } }); }
public static ObjectStateEntry AttachAsModifiedInternal <T>(T current, T original, ObjectContext objectContext) { ObjectStateEntry objectStateEntry = objectContext.ObjectStateManager.GetObjectStateEntry(current); objectStateEntry.ApplyOriginalValues(original); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); AttributeCollection attributes = TypeDescriptor.GetAttributes(typeof(T)); //bool flag = attributes[typeof(RoundtripOriginalAttribute)] != null; foreach (FieldMetadata current2 in objectStateEntry.CurrentValues.DataRecordInfo.FieldMetadata) { string name = objectStateEntry.CurrentValues.GetName(current2.Ordinal); PropertyDescriptor propertyDescriptor = properties[name]; if (propertyDescriptor != null /* && propertyDescriptor.Attributes[typeof(RoundtripOriginalAttribute)] == null && * !flag && propertyDescriptor.Attributes[typeof(ExcludeAttribute)] == null*/) { objectStateEntry.SetModifiedProperty(name); } } return(objectStateEntry); }
public static void Update <TEntity, TKey>(this DbContext dbContext, Expression <Func <TEntity, object> > propertyExpression, params TEntity[] entities) where TEntity : EntityBase <TKey> { if (propertyExpression == null) { throw new ArgumentNullException("propertyExpression"); } if (entities == null) { throw new ArgumentNullException("entities"); } ReadOnlyCollection <MemberInfo> memberInfos = ((dynamic)propertyExpression.Body).Members; foreach (TEntity entity in entities) { DbSet <TEntity> dbSet = dbContext.Set <TEntity>(); try { DbEntityEntry <TEntity> entry = dbContext.Entry(entity); //entry.State = EntityState.Unchanged; foreach (MemberInfo memberInfo in memberInfos) { entry.Property(memberInfo.Name).IsModified = true; } } catch (InvalidOperationException) { TEntity originalEntity = dbSet.Local.Single(m => Equals(m.SysNo, entity.SysNo)); ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; ObjectStateEntry objectEntry = objectContext.ObjectStateManager.GetObjectStateEntry(originalEntity); objectEntry.ApplyCurrentValues(entity); objectEntry.ChangeState(EntityState.Unchanged); foreach (MemberInfo memberInfo in memberInfos) { objectEntry.SetModifiedProperty(memberInfo.Name); } } } }
/// <summary> /// Sets a single property on an entity as modified on the specified <see cref="ObjectContext"/>. /// </summary> /// <remarks> /// This method is thread-safe. /// </remarks> /// <typeparam name="TEntity">The type of the entity</typeparam> /// <typeparam name="TProp">The type of the property</typeparam> /// <param name="entity">The entity</param> /// <param name="propertySelector"> /// A lambda (expression tree) that returns the property on <typeparamref name="TEntity"/>. /// </param> /// <param name="context">The <see cref="ObjectContext"/> that the entity is attached to</param> /// <returns>The entity (for fluent syntax)</returns> public static TEntity SetModified <TEntity, TProp>(this TEntity entity, Expression <Func <TEntity, TProp> > propertySelector, ObjectContext context) where TEntity : IEntityWithKey { MemberExpression memberExpr = propertySelector.Body as MemberExpression; if (memberExpr == null) { throw new ArgumentException("The expression " + propertySelector + " is not a valid expression for this method. It must return a property on the parameter."); } PropertyInfo propertyInfo = memberExpr.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException("The expression " + propertySelector + " is not a valid expression for this method. It must return a property on the parameter."); } ObjectStateEntry stateEntry = context.ObjectStateManager.GetObjectStateEntry(entity.EntityKey); stateEntry.SetModifiedProperty(propertyInfo.Name); return(entity); }
public void SetModifiedProperty(string propertyName) { _stateEntry.SetModifiedProperty(propertyName); }