Last active
September 2, 2019 14:02
-
-
Save wi7a1ian/f19d81f217f818e68baec105a1511df2 to your computer and use it in GitHub Desktop.
Generic async method for reading all db rows in c# #csharp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected async Task<IEnumerable<T>> GetAllRowsAsync<T>(DbConnection conn, string query, Func<DbDataReader, Task<T>> asyncMapper, CancellationToken token) | |
where T : class | |
{ | |
IList<T> result = new List<T>(); | |
using (conn) | |
using (var cmd = conn.CreateCommand()) | |
{ | |
await conn.OpenAsync(token); | |
cmd.CommandText = query; | |
using (var reader = await cmd.ExecuteReaderAsync(token)) | |
{ | |
while (await reader.ReadAsync(token)) | |
{ | |
T mappedObj = await asyncMapper(reader); | |
if(mappedObj != null) | |
{ | |
result.Add(mappedObj); | |
} | |
} | |
} | |
} | |
return result; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private const string query = @"SELECT * FROM Sth"; | |
public async Task<IEnumerable<SthEntry>> GetSthAsync(CancellationToken token) | |
{ | |
return await GetAllRowsAsync(new SqlConnection(connectionString), query, async (reader) => | |
{ | |
return new SthEntry | |
{ | |
Id = reader.GetInt32(0), | |
Name = reader.GetString(1), | |
Email = (!await reader.IsDBNullAsync(3)) ? reader.GetString(3) : string.Empty, | |
}; | |
}, token); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment