日期:2014-05-20  浏览次数:21015 次

求LinQ 更新字段语法
SQL
SQL code

update Table set col1 = '123' where id = 3



怎样把他转换为LinQ语法,在一个List<Entity>集合里面.不是LinQ to Sql的,我只是想把一个对象里面某个字段的值做一下修改。

------解决方案--------------------
(from e in List<Entity>
where e.id==3
select e).FirstOrDefault().coll="123";
------解决方案--------------------
List<Entity>.ForEach(e=> {if(e.id==3)e.col1="123";});
------解决方案--------------------
写一个扩展,大概思路是这样的,发我在实际中的转化
C# code
  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;
        }