cmd.ReadToList - lobodava/artisan-orm GitHub Wiki

SqlCommand extension method, which reads result of a single select with multiple records to a List 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 an IList<T> (a new list, or the supplied destination list).
Sync method Async method
ReadToList<T>() ReadToListAsync<T>()

If select returns nothing, then ReadToList<T>() returns an empty List<T>.

In the source being prepared for 4.1.0, an explicit createFunc handles every returned row, including scalar/nullable results and SQL NULL in column zero. Without a factory, simple types use the normal scalar path. When a destination list is supplied, rows are appended and that same list is returned; an empty result leaves it unchanged. See Inline Mappers.

Examples:

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

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

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

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

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

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