日期:2014-05-20 浏览次数:21197 次
update Table set col1 = '123' where id = 3
  static class UpdateExtensions
    {
        private static Command GetCommands<Entity>(Expression<Func<Entity, bool>> Predicate, Expression<Func<Entity, Entity>> Updater) where Entity : class,IEntity
        {
            ConditionBuilder Builder = new ConditionBuilder();
            Builder.Build(Predicate.Body);
            string sqlCondition = Builder.Condition;
            //获取Update的赋值语句
            var updateMemberExpr = (MemberInitExpression)Updater.Body;
            var updateMemberCollection = updateMemberExpr.Bindings.Cast<MemberAssignment>().Select(c => new
            {
                Name = c.Member.Name,
                Value = ((ConstantExpression)c.Expression).Value
            });
            int i = Builder.Arguments.Length;
            Type type = typeof(Entity);
            var tableAttribute = type.GetCustomAttributes(false).OfType<System.ComponentModel.DataAnnotations.TableAttribute>().FirstOrDefault();
            string Table = tableAttribute == null ? type.Name : tableAttribute.Name;
            if (Table.Length > 2 && Table.StartsWith("DB", StringComparison.CurrentCultureIgnoreCase))
            {
                Table = Table.Substring(2, Table.Length - 2);
            }
            var PreTable = System.Configuration.ConfigurationManager.AppSettings["PreTable"];
            Table = PreTable == null ? Table : PreTable + "_" + Table;
            string sqlUpdateBlock = string.Join(", ", updateMemberCollection.Select(c => string.Format("[{0}]={1}", c.Name, "{" + (i++) + "}")).ToArray());
            string commandText = string.Format("Update [{0}] Set {1} Where {2}", Table, sqlUpdateBlock, sqlCondition);
            //获取SQL参数数组 (包括查询参数和赋值参数)
            var args = Builder.Arguments.Union(updateMemberCollection.Select(c => c.Value)).ToArray();
            return new Command() { Text = commandText, args = args };
        }
        /// <summary>
        /// 执行UpDate返回影响的条数
        /// </summary>
        public static int UpdateEntity<Entity>(this EFDbContext<Entity> Context, Expression<Func<Entity, bool>> Predicate, Expression<Func<Entity, Entity>> Updater) where Entity : class,IEntity
        {
            Command com = GetCommands<Entity>(Predicate, Updater);
            int Result = Context.Database.ExecuteSqlCommand(com.Text, com.args);
            return Result;
        }