首页 > 代码库 > Entity Framework 通过Lambda表达式更新指定的字段

Entity Framework 通过Lambda表达式更新指定的字段

本来需要EF来更新指定的字段,后来在园子里找到了代码

var StateEntry = ((IObjectContextAdapter)dbContext).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity);
StateEntry.SetModifiedProperty(property);

今天看Dos.ORM的源码发现了如何找到Lambda表达式里面的属性值

 public string GetFieldNameByLambda(Expression exprBody)
        {
            var property = "";
            if (exprBody is UnaryExpression)
            {
                property = ((MemberExpression)((UnaryExpression)exprBody).Operand).Member.Name;
            }
            else if (exprBody is MemberExpression)
            {
                property = ((MemberExpression)exprBody).Member.Name;
            }
            else if (exprBody is ParameterExpression)
            {
                property = ((ParameterExpression)exprBody).Type.Name;
            }
            return property;
        }

然后综合一下就可以了

 /// <summary>
        /// 根据Lambda表达式更新字段
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="property"></param>
        /// <returns></returns>
        public TEntity UpdateEntityField(TEntity entity, params Expression<Func<TEntity, object>>[] property)
        {
            IList<string> Pros = new List<string>();
            foreach (var item in property)
            {
                Pros.Add(GetFieldNameByLambda(item.Body));
            }
            return UpdateEntityField(entity,Pros.ToArray());
        }

 

Entity Framework 通过Lambda表达式更新指定的字段