转 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;
                }
            }
        } 

 

posted @ 2014-12-20 14:49  英雄饶命啊  阅读(903)  评论(0)    收藏  举报