Proposal for db.Query<string>()

Jun 15, 2011 at 8:08 AM

Is it possible something like this?

/// <summary>
        /// Returns the results of a SP query.
        /// </summary>
        /// <returns>Returns a list of the specified type.</returns>
        public ICollection<T> Query<T>(string sql, ICollection<T> entityList)
        {
            if (entityList == null)
                throw new ArgumentNullException("ICollection instance cannot be null.");

            if (string.IsNullOrEmpty(sql))
                throw new ArgumentNullException("A stored procedure name has not been specified for 'Query'.");

            var scalarTypes = new List<Type> {typeof(string), typeof(int), typeof(long)}; //etc
            bool scalarTypeUsed = false;
            
            Type entityType = typeof(T);
            Command.CommandText = sql;

            MappingHelper mappingHelper = null;
            ColumnMapCollection mappings = null;

            if (!scalarTypes.Contains(entityType))
            {
                mappingHelper = new MappingHelper(Command);
                mappings = MapRepository.Instance.GetColumns(entityType);
            }
            else
                scalarTypeUsed = true;

            try
            {
                OpenConnection();
                using (DbDataReader reader = Command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (scalarTypeUsed)
                            entityList.Add((T) reader.GetValue(0));
                        else
                        {
                            if (LoadEntity != null)
                            {
                                // Delegates the loading task to the caller
                                LoadEntity(this, new LoadEntityEventArgs(reader));
                            }
                            else
                            {
                                // Create new entity
                                object ent = mappingHelper.CreateAndLoadEntity<T>(mappings, reader, false);

                                // Add entity to return list
                                entityList.Add((T) ent);
                            }
                        }
                    }
                }
            }
            finally
            {
                CloseConnection();
            }

            return entityList;
        }

Coordinator
Jun 15, 2011 at 2:26 PM

Yes, that is a good idea. 

Coordinator
Jan 2, 2012 at 6:56 PM

Vitidev,

I just implemented your idea to allow primitives for the following methods:

- Query<string>("SELECT [Name] FROM tbl")

- Find<string>("SELECT [Name] FROM tbl WHERE ID=1")

By the way, great suggestions. 

Jordan