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 connection;
- Executes SqlDataReader with
CommandBehavior.SingleResultflag; - Reads all records of the first
select; - Closes connection;
- Returns result of T[] type.
| Sync method | Async method |
|---|---|
ReadToArray<T>() |
ReadToArrayAsync<T>() |
If select returns nothing, then ReadToArray<T>() returns an empty T[].
return cmd.ReadToArray<int>(); // select Id from 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 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>();
});
}