cmd.ReadToArray - lobodava/artisan-orm GitHub Wiki

SqlCommand extension method, which reads result of a single select with multiple records to a Array of value types (int, date, bool), strings or objects.

This method:

  • Opens the connection if it was closed;
  • Executes SqlDataReader with CommandBehavior.SingleResult flag;
  • Reads all records of the first select;
  • Disposes the reader and closes the connection only if this call opened it;
  • Returns result of T[] type.
Sync method Async method
ReadToArray<T>() ReadToArrayAsync<T>()

If select returns nothing, then ReadToArray<T>() returns an empty T[].

In the source being prepared for 4.1.0, a supplied createFunc handles each row, including scalar/nullable output types and SQL NULL in column zero. It controls the source columns and null substitution. The corresponding async factory overload follows the same contract. See Inline Mappers.

Examples:

return cmd.ReadToArray<int>();       // select Id from vwUsers order by Id
return cmd.ReadToArray<bool>();      // select cast(0 as bit) union all select cast(1 as bit)
return cmd.ReadToArray<string>();    // select 'Lorem ipsum' union all select 'dolor sit amet'
return cmd.ReadToArray<User>();      // select * from vwUsers order by Id
return cmd.ReadToArray<Record>();    // select * from vwRecords order by Id

// or async version
return cmd.ReadToArrayAsync<int>();   // select Id from vwUsers order by Id

Example of ReadToArray<T>() in repository method:

public User[] GetUsers(int id)
{
    return GetByCommand(cmd =>
    {
        cmd.UseSql("select * from vwUsers order by Id");
        return cmd.ReadToArray<User>();
    });
}

Example of ReadToArrayAsync<T>() in async repository method:

public async Task<User[]> GetUsersAsync()
{
    return await GetByCommandAsync(cmd =>
    {
        cmd.UseProcedure("dbo.GetUsers");
        return cmd.ReadToArrayAsync<User>();
    });
}
⚠️ **GitHub.com Fallback** ⚠️