Ejemplo n.º 1
0
        protected SqlQueryableProvider(DbConnection connection, SqlQueryVisitor visitor)
        {
            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connection));
            }
            if (visitor == null)
            {
                throw new ArgumentNullException(nameof(visitor));
            }

            this.connection = connection;
            this.visitor    = visitor;
        }
        public static IEnumerable <Record> ExecuteQuery(this DbConnection connection, ASourceExpression expression, SqlQueryVisitor visitor)
        {
            // Create the outer select expression
            SelectExpression select = expression as SelectExpression;

            if (select == null)
            {
                select = new SelectExpression(expression, expression.Fields);
            }

            // Ensure the connection is open
            if (connection.State != ConnectionState.Open)
            {
                throw new InvalidOperationException("The connection must be open to execute a query.");
            }

            // Create the command
            LinkedList <Record> items = new LinkedList <Record>();

            using (DbCommand command = connection.CreateCommand())
            {
                // Prepare the query
                Query query = visitor.GenerateQuery(select);
                command.CommandText = query.Sql;
                foreach (KeyValuePair <string, object> pair in query.Parameters)
                {
                    command.AddParameter(pair.Key, pair.Value);
                }

                // Execute the query
                using (DbDataReader reader = command.ExecuteReader())
                {
                    ILookup <string, CommandField> fields = reader.GetFieldMap(select.Fields);
                    while (reader.Read())
                    {
                        // Read the row of the result set
                        Dictionary <string, RecordItem> row = fields
                                                              .Select(x => ReadItem(reader, x, x.Key))
                                                              .ToDictionary(x => x.Key);

                        // At this point the row has been created
                        items.AddLast(new Record(row));
                    }
                }
            }
            return(items);
        }