Example #1
0
        /// <summary>
        ///     Generate a complete list before returning.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity to use, must have an mapper registered in <see cref="EntityMappingProvider"/>.</typeparam>
        /// <param name="cmd">Command to invoke <c>ExecuteReader()</c> on.</param>
        /// <param name="mapper">Mapper to use when converting the rows to entities</param>
        /// <returns>A collection of entities, or an empty collection if no entities are found.</returns>
        /// <example>
        ///     <code>
        /// <![CDATA[
        /// public void FindByName(string firstName, string lastName)
        /// {
        ///     using (var command = connection.CreateCommand())
        ///     {
        ///         cmd.CommandText = "SELECT * FROM Users WHERE ";
        ///         if (lastName != null)
        ///         {
        ///             cmd.AddParameter("firstName", firstName + "%");
        ///             cmd.CommandText += "FirstName LIKE @firstName AND ";
        ///         }
        ///         if (lastName != null)
        ///         {
        ///             cmd.AddParameter("lastName", lastName + "%");
        ///             cmd.CommandText += "LastName LIKE @lastName AND ";
        ///         }
        ///
        ///         cmd.CommandText = cmd.CommandText.Remove(cmd.CommandText.Length - 4, 4);
        ///         return cmd.ToList<User>();
        ///     }
        /// }
        /// ]]>
        /// </code>
        /// </example>
        public static IList <TEntity> ToList <TEntity>(this IDbCommand cmd, ICrudEntityMapper <TEntity> mapper)
        {
            if (cmd == null)
            {
                throw new ArgumentNullException("cmd");
            }
            if (mapper == null)
            {
                throw new ArgumentNullException("mapper");
            }

            try
            {
                var items = new List <TEntity>(10);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var entity = mapper.Create(reader);
                        mapper.Map(reader, entity);
                        items.Add((TEntity)entity);
                    }
                }
                return(items);
            }
            catch (Exception e)
            {
                throw cmd.CreateDataException(e);
            }
        }
Example #2
0
        /// <summary>
        ///     Fetches the first row and maps it as an entity (if found).
        /// </summary>
        /// <typeparam name="TEntity">Type of entity to use, must have an mapper registered in <see cref="EntityMappingProvider"/>.</typeparam>
        /// <param name="cmd">Command to invoke <c>ExecuteReader()</c> on.</param>
        /// <param name="mapper">Mapper which can convert the db row to an entity.</param>
        /// <returns>Entity if found; otherwise <c>null</c>.</returns>
        /// <example>
        ///     <code>
        /// <![CDATA[
        /// public void FindUser(string id)
        /// {
        ///     using (var command = connection.CreateCommand())
        ///     {
        ///         cmd.CommandText = "SELECT * FROM Users WHERE Id = @id";
        ///         cmd.AddParameter("id", userId);
        ///         return cmd.FirstOrDefault<User>(new MyCustomUserMapper());
        ///     }
        /// }
        /// ]]>
        /// </code>
        /// </example>
        public static TEntity FirstOrDefault <TEntity>(this IDbCommand cmd, ICrudEntityMapper <TEntity> mapper)
        {
            if (cmd == null)
            {
                throw new ArgumentNullException("cmd");
            }
            if (mapper == null)
            {
                throw new ArgumentNullException("mapper");
            }

            try
            {
                using (var reader = cmd.ExecuteReader())
                {
                    if (!reader.Read())
                    {
                        return(default(TEntity));
                    }

                    var entity = mapper.Create(reader);
                    mapper.Map(reader, entity);
                    return((TEntity)entity);
                }
            }
            catch (Exception e)
            {
                throw cmd.CreateDataException(e);
            }
        }
        /// <summary>
        ///     Generate a complete list before returning.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity to map</typeparam>
        /// <param name="connection">Connection to invoke <c>ExecuteReaderAsync()</c> on (through a created <c>DbCommand</c>).</param>
        /// <param name="mapping">Mapping used to translate from db table rows to .NET object</param>
        /// <param name="query">Query or short query (<c><![CDATA["projectId = @id AND dateCreated < @minDate"]]></c>)</param>
        /// <param name="parameters">
        ///     Anonymous object (<c>new { id = dto.ProjectId, @minDate = dto.MinDate }</c>), a dictionary or
        ///     a value array
        /// </param>
        /// <returns>A list which is generated asynchronously.</returns>
        /// <remarks>
        ///     <para>
        ///         For more information about the "query" and "parameters" arguments, see
        ///         <see cref="CommandExtensions.ApplyQuerySql{TEntity}" />.
        ///     </para>
        ///     <para>
        ///         The returned enumerator will not map each row until it's requested. To be able to do that the
        ///         connection/command/datareader is
        ///         kept open until the enumerator is disposed. Hence it's important that you make sure that the enumerator is
        ///         disposed when you are
        ///         done with it.
        ///     </para>
        ///     <para>Uses <see cref="EntityMappingProvider" /> to find the correct <c><![CDATA[IEntityMapper<TEntity>]]></c>.</para>
        /// </remarks>
        /// <example>
        ///     <code>
        /// // All these examples are valid:
        /// <![CDATA[
        /// var users = await connection.ToListAsync<User>("Age < 10");
        /// var users = await connection.ToListAsync<User>("SELECT * FROM Users WHERE Age = 37");
        /// var users = await connection.ToListAsync<User>("FirstName = @name", new { name = user.FirstName });
        /// var users = await connection.ToListAsync<User>("FirstName = @1 AND Age < @2", 'A%', 35);
        /// var users = await connection.ToListAsync<User>("SELECT * FROM Users WHERE Age = @age LIMIT 1, 10", new { age = submittedAge });
        /// var users = await connection.ToListAsync<User>("SELECT * FROM Users WHERE Age = @1 LIMIT 1, 10", user.FirstName);
        /// ]]>
        /// </code>
        /// </example>
        public static async Task <List <TEntity> > ToListAsync <TEntity>(this IDbConnection connection,
                                                                         ICrudEntityMapper <TEntity> mapping, string query, params object[] parameters)
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }
            if (mapping == null)
            {
                throw new ArgumentNullException("mapping");
            }

            var cmd = connection.CreateDbCommand();

            cmd.ApplyQuerySql(mapping, query, parameters);

            try
            {
                var items = new List <TEntity>();
                using (var reader = await cmd.ExecuteReaderAsync())
                {
                    while (await reader.ReadAsync())
                    {
                        var entity = mapping.Create(reader);
                        mapping.Map(reader, entity);
                        items.Add((TEntity)entity);
                    }
                }
                return(items);
            }
            catch (Exception e)
            {
                throw cmd.CreateDataException(e);
            }
        }
Example #4
0
        /// <summary>
        ///     Generate a complete list before returning.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity to map</typeparam>
        /// <param name="unitOfWork">Connection to invoke <c>ExecuteReader()</c> on (through a created <c>DbCommand</c>).</param>
        /// <param name="mapping">Mapping used to translate from db table rows to .NET object</param>
        /// <param name="query">Query or short query (<c><![CDATA["projectId = @id AND dateCreated < @minDate"]]></c>)</param>
        /// <param name="parameters">Anonymous object (<c>new { id = dto.ProjectId, @minDate = dto.MinDate }</c>), a dictionary or a value array</param>
        /// <returns>A list.</returns>
        /// <remarks>
        ///     <para>
        ///         For more information about the "query" and "parameters" arguments, see <see cref="CommandExtensions.ApplyQuerySql{TEntity}"/>.
        ///     </para>
        ///     <para>
        ///         The returned enumerator will not map each row until it's requested. To be able to do that the
        ///         connection/command/datareader is
        ///         kept open until the enumerator is disposed. Hence it's important that you make sure that the enumerator is
        ///         disposed when you are
        ///         done with it.
        ///     </para>
        ///     <para>Uses <see cref="EntityMappingProvider" /> to find the correct <c><![CDATA[IEntityMapper<TEntity>]]></c>.</para>
        /// </remarks>
        /// <example>
        /// <code>
        /// // All these examples are valid:
        /// <![CDATA[
        /// var users = unitOfWork.ToList<User>("Age < 10");
        /// var users = unitOfWork.ToList<User>("SELECT * FROM Users WHERE Age = 37");
        /// var users = unitOfWork.ToList<User>("FirstName = @name", new { name = user.FirstName });
        /// var users = unitOfWork.ToList<User>("FirstName = @1 AND Age < @2", 'A%', 35);
        /// var users = unitOfWork.ToList<User>("SELECT * FROM Users WHERE Age = @age LIMIT 1, 10", new { age = submittedAge });
        /// var users = unitOfWork.ToList<User>("SELECT * FROM Users WHERE Age = @1 LIMIT 1, 10", user.FirstName);
        /// ]]>
        /// </code>
        /// </example>
        public static IList <TEntity> ToList <TEntity>(this IAdoNetUnitOfWork unitOfWork, ICrudEntityMapper <TEntity> mapping, string query, params object[] parameters)
        {
            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unitOfWork");
            }
            if (mapping == null)
            {
                throw new ArgumentNullException("mapping");
            }

            var cmd = unitOfWork.CreateDbCommand();

            try
            {
                cmd.ApplyQuerySql(mapping, query, parameters);

                var items = new List <TEntity>();
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var entity = mapping.Create(reader);
                        mapping.Map(reader, entity);
                        items.Add((TEntity)entity);
                    }
                }
                return(items);
            }
            catch (Exception e)
            {
                throw cmd.CreateDataException(e);
            }
        }
Example #5
0
        /// <summary>
        ///     Generate a complete list before returning.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity to map</typeparam>
        /// <param name="unitOfWork">Unit of work to invoke <c>ExecuteReaderAsync()</c> on (through a created <c>DbCommand</c>).</param>
        /// <param name="mapping">Mapping used to translate from db table rows to .NET object</param>
        /// <param name="query">Query or short query (<c><![CDATA["projectId = @id AND dateCreated < @minDate"]]></c>)</param>
        /// <param name="parameters">Anonymous object (<c>new { id = dto.ProjectId, @minDate = dto.MinDate }</c>), a dictionary or a value array</param>
        /// <returns>A list which is generated asynchronously.</returns>
        /// <remarks>
        ///     <para>
        ///         For more information about the "query" and "parameters" arguments, see <see cref="CommandExtensions.ApplyQuerySql{TEntity}"/>.
        ///     </para>
        ///     <para>
        ///         The returned enumerator will not map each row until it's requested. To be able to do that the
        ///         connection/command/datareader is
        ///         kept open until the enumerator is disposed. Hence it's important that you make sure that the enumerator is
        ///         disposed when you are
        ///         done with it.
        ///     </para>
        ///     <para>Uses <see cref="EntityMappingProvider" /> to find the correct <c><![CDATA[IEntityMapper<TEntity>]]></c>.</para>
        /// </remarks>
        /// <example>
        /// <code>
        /// // All these examples are valid:
        /// <![CDATA[
        /// var users = await unitOfWork.ToListAsync<User>("Age < 10");
        /// var users = await unitOfWork.ToListAsync<User>("SELECT * FROM Users WHERE Age = 37");
        /// var users = await unitOfWork.ToListAsync<User>("FirstName = @name", new { name = user.FirstName });
        /// var users = await unitOfWork.ToListAsync<User>("FirstName = @1 AND Age < @2", 'A%', 35);
        /// var users = await unitOfWork.ToListAsync<User>("SELECT * FROM Users WHERE Age = @age LIMIT 1, 10", new { age = submittedAge });
        /// var users = await unitOfWork.ToListAsync<User>("SELECT * FROM Users WHERE Age = @1 LIMIT 1, 10", user.FirstName);
        /// ]]>
        /// </code>
        /// </example>
        public static async Task <List <TEntity> > ToListAsync <TEntity>(this IAdoNetUnitOfWork unitOfWork, ICrudEntityMapper <TEntity> mapping, string query, params object[] parameters)
        {
            if (unitOfWork == null)
            {
                throw new ArgumentNullException("unitOfWork");
            }
            if (mapping == null)
            {
                throw new ArgumentNullException("mapping");
            }
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            var cmd = unitOfWork.CreateDbCommand();

            cmd.ApplyQuerySql(mapping, query, parameters);

            var items = new List <TEntity>();

            using (var reader = await cmd.ExecuteReaderAsync())
            {
                while (await reader.ReadAsync())
                {
                    var entity = mapping.Create(reader);
                    mapping.Map(reader, entity);
                    items.Add((TEntity)entity);
                }
            }
            return(items);
        }