Exemple #1
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</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>("SELECT * FROM Users WHERE Age = 37");
        /// var users = unitOfWork.ToList<User>("SELECT * FROM Users WHERE FirstName = @name", new { name = user.FirstName });
        /// var users = unitOfWork.ToList<User>("SELECT * FROM Users WHERE FirstName = @1 AND Age < @2", 'A%', 35);
        /// ]]>
        /// </code>
        /// </example>
        public static IList <TEntity> ToList <TEntity>(this IAdoNetUnitOfWork unitOfWork, IEntityMapper <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 <TEntity>(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);
            }
        }
        /// <summary>
        ///     Generate a complete list before returning.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity to map</typeparam>
        /// <param name="cmd">Command to invoke <c>ExecuteReaderAsync()</c> on.</param>
        /// <param name="mapper">Mapper to use when converting rows to entities</param>
        /// <returns>A list which is generated asynchronously.</returns>
        /// <remarks>
        ///     <para>
        ///         Make sure that you <c>await</c> the method, as nothing the reader is not disposed directly if you don't.
        ///     </para>
        /// </remarks>
        public static async Task <IList <TEntity> > ToListAsync <TEntity>(this IDbCommand cmd,
                                                                          IEntityMapper <TEntity> mapper)
        {
            if (cmd == null)
            {
                throw new ArgumentNullException("cmd");
            }
            if (mapper == null)
            {
                throw new ArgumentNullException("mapper");
            }

            var items   = new List <TEntity>();
            var command = GetDbCommandFromInterface(cmd);

            using (var reader = await command.ExecuteReaderAsync())
            {
                while (await reader.ReadAsync())
                {
                    var entity = mapper.Create(reader);
                    mapper.Map(reader, entity);
                    items.Add((TEntity)entity);
                }
            }
            return(items);
        }
        /// <summary>
        ///     Fetches the first row if found.
        /// </summary>
        /// <param name="cmd">Command to invoke <c>ExecuteReaderAsync()</c> on.</param>
        /// <param name="mapper">Mapper used to convert rows to entities</param>
        /// <returns>
        ///     Entity if found; otherwise <c>null</c>.
        /// </returns>
        /// <remarks>
        ///     <para>Use this method when an entity is expected to be returned.</para>
        /// </remarks>
        /// <example>
        ///     <code>
        /// <![CDATA[
        /// public async Task<User> GetUser(int userId)
        /// {
        ///     using (var command = connection.CreateCommand())
        ///     {
        ///         cmd.CommandText = "SELECT * FROM Users WHERE Id = @id";
        ///         cmd.AddParameter("id", userId);
        ///         return await cmd.FirstOrDefaultAsync<User>(new MyCustomMapping());
        ///     }
        /// }
        /// ]]>
        /// </code>
        /// </example>
        /// <seealso cref="CrudEntityMapper{TEntity}" />
        public static async Task <TEntity> FirstOrDefaultAsync <TEntity>(this IDbCommand cmd,
                                                                         IEntityMapper <TEntity> mapper)
        {
            if (cmd == null)
            {
                throw new ArgumentNullException("cmd");
            }
            if (mapper == null)
            {
                throw new ArgumentNullException("mapper");
            }

            var command = GetDbCommandFromInterface(cmd);

            using (var reader = await command.ExecuteReaderAsync())
            {
                if (!await reader.ReadAsync())
                {
                    return(default(TEntity));
                }

                var entity = (TEntity)mapper.Create(reader);
                mapper.Map(reader, entity);
                return(entity);
            }
        }
Exemple #4
0
        /// <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</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}(IEntityMapper,string,object[])" />.
        ///     </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>("SELECT * FROM Users WHERE Age = 37");
        /// var users = await connection.ToListAsync<User>("SELECT * FROM Users WHERE FirstName = @name", new { name = user.FirstName });
        /// var users = await connection.ToListAsync<User>("SELECT * FROM Users WHERE FirstName = @1 AND Age < @2", 'A%', 35);
        /// ]]>
        /// </code>
        /// </example>
        public static async Task <List <TEntity> > ToListAsync <TEntity>(this IDbConnection connection,
                                                                         IEntityMapper <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 <TEntity>(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);
            }
        }
Exemple #5
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, IEntityMapper <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);
            }
        }
Exemple #6
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, IEntityMapper <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);
            }
        }