代码改变世界

ADO.NET Entity Framework 批量更新/批量删除扩展

2011-07-30 11:57  ※森林小居※  阅读(6875)  评论(33编辑  收藏  举报

        一直都在想着用ADO.NET Entity Framework开发项目,只是Entity Framework 中不能同时更新多条记录。所以一直没有使作其开发。最近在看到了一些LINQ TO SQL的一些扩展方法,本人就LINQ TO SQL的扩展也实行了对Entity Framework扩展。主要代码如下:

       以下是更新的扩展代码:

   

        /// <summary>
        /// 更新满足条件的实体,返回更新实体的条数
         /// </summary>
        /// <typeparam name="T">更新的类型</typeparam>
        /// <param name="Entity">实体类</param>
        /// <param name="Predicate">更新的条件</param>
        /// <param name="Updater">更新的值</param>
        /// <returns>int</returns>
        public static int UpdateEntity<T>(this ObjectSet<T> Entity, Expression<Func<T, bool>> Predicate, Expression<Func<T, T>> Updater) where T : class
        {
            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;
            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}", Entity.EntitySet.Name, sqlUpdateBlock, sqlCondition);
            //获取SQL参数数组 (包括查询参数和赋值参数)
            var args = Builder.Arguments.Union(updateMemberCollection.Select(c => c.Value)).ToArray();
            var Result = Entity.Context.ExecuteStoreCommand(commandText, args);
            return Result;
        }

 

    以下是删除方法的扩展:

         /// <summary>
         /// 删除满足条件的实体,返回删除实体的条数
          /// </summary>
        /// <typeparam name="T">删除的类型</typeparam>
        /// <param name="Entity">实体类</param>
        /// <param name="Predicate">删除的条件</param>
        /// <returns>int</returns>
        public static int DeleteEntity<T>(this ObjectSet<T> Entity, Expression<Func<T, bool>> Predicate) where T : class
        {
            //查询条件表达式转换成SQL的条件语句
            ConditionBuilder Builder = new ConditionBuilder();
            Builder.Build(Predicate.Body);
            string sqlCondition = Builder.Condition;
            //获取SQL参数数组 
            var args = Builder.Arguments;
            var Result = Entity.Context.ExecuteStoreCommand("Delete  From  " + Entity.EntitySet.Name + " Where " + sqlCondition, args);
            return Result;
        }

 

        批量更新/批量删除主要是通过拼接SQL语句执行。还需高手多多指点。点击此处下载源码