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 connection;
  • Executes SqlDataReader with CommandBehavior.SingleResult flag;
  • Reads all records of the first select;
  • Closes connection;
  • Returns result of List type.
Sync method Async method
ReadToList<T>() ReadToListAsync<T>()

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

Examples:

return cmd.ReadToList<int>();       // select Id from 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 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** ⚠️