转 EF update 只修改想要修改的字段
http://stackoverflow.com/questions/5749110/readonly-properties-in-ef-4-1/5749469#5749469
public void Update(T entity, params Expression<Func<T, object>>[] properties) { _dbSet.Attach(entity); DbEntityEntry<T> entry = _context.Entry(entity); foreach (var selector in properties) { entry.Property(selector).IsModified = true; } }
You will call it like:
repo.Update(entity, e => e.Name, e => e.Description);
or:
public int Update(T entity, Expression<Func<T, object>>[] properties) { DatabaseContext.Entry(entity).State = EntityState.Unchanged; foreach (var property in properties) { var propertyName = ExpressionHelper.GetExpressionText(property); DatabaseContext.Entry(entity).Property(propertyName).IsModified = true; } return DatabaseContext.SaveChangesWithoutValidation(); }
"As you can see, it takes as its second parameter an expression of a function. This will let use this method by specifying in a Lambda expression which property to update."
...Update(Model, d=>d.Name); //or ...Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn);
以下是在项目中使用的:
/// <summary> /// 修改--该方法只修改指定的属性 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity"></param> /// <param name="properties"></param> public int Update(T entity, params Expression<Func<T, object>>[] properties) { DbEntityEntry<T> entry = this.Entry(entity); entry.State = EntityState.Unchanged; foreach (var selector in properties) { entry.Property(selector).IsModified = true; } bool isReturn = base.Configuration.ValidateOnSaveEnabled; try { if (isReturn) { base.Configuration.ValidateOnSaveEnabled = false; } return base.SaveChanges(); } finally { if (isReturn) { base.Configuration.ValidateOnSaveEnabled = true; } } }
用对方法才有效率,做对事情才有效果
“麻烦”是自己“处理”不当的结果
“困难”是自己“学习”不够的反射
“挫折”是自己“努力”不足的代价
“麻烦”是自己“处理”不当的结果
“困难”是自己“学习”不够的反射
“挫折”是自己“努力”不足的代价
浙公网安备 33010602011771号