private static DbCommand GetUpdateCommand <TEntity>(this Table <TEntity> table, Expression <Func <TEntity, bool> > filter, Expression <Func <TEntity, TEntity> > evaluator) where TEntity : class { DbCommand command = (table.Context as SqlDataContext).SqlCommand; command.CommandType = CommandType.Text; command.Parameters.Clear(); //查询条件表达式转换成SQL的条件语句 ConditionBuilder builder = new ConditionBuilder(); builder.Build(filter.Body, command); string commandWhere = command.CommandText; var set = new StringBuilder(); var entityType = typeof(TEntity); var metaTable = table.Context.Mapping.GetTable(entityType); var tableName = "[" + metaTable.TableName + "]"; evaluator.Visit <MemberInitExpression>(delegate(MemberInitExpression expression) { set.Append(GetDbSetStatement <TEntity>(expression, table, command)); return(expression); }); command.CommandText = "UPDATE " + tableName + " " + set + " WHERE " + commandWhere; return(command); }
/// <summary> /// 删除数据 /// </summary> public static int Delete <TEntity>(this Table <TEntity> table, Expression <Func <TEntity, bool> > filter) where TEntity : class { DbCommand cmd = (table.Context as SqlDataContext).SqlCommand; cmd.CommandType = CommandType.Text; cmd.Parameters.Clear(); //查询条件表达式转换成SQL的条件语句 ConditionBuilder builder = new ConditionBuilder(); builder.Build(filter.Body, cmd); string commandWhere = cmd.CommandText; //获取表名 string tableName = "[" + table.Context.Mapping.GetTable(typeof(TEntity)).TableName + "]"; //SQL命令 string commandText = string.Format("DELETE FROM {0} WHERE {1}", tableName, commandWhere); cmd.CommandText = commandText; if (table.Context.Connection.State != ConnectionState.Open) { table.Context.Connection.Open(); } if (table.Context.Transaction != null) { cmd.Transaction = table.Context.Transaction; } return(cmd.ExecuteNonQuery()); }