Skip to content

Instantly share code, notes, and snippets.

@ankitvijay
Last active Mar 13, 2020
Embed
What would you like to do?
API After IAsynceEnumerable changes
// Import Nuget package: System.Linq.Async
public async Task<IAsyncEnumerable<Item>> GetItems(int id)
{
var reader = await _connection.QueryMultipleAsync(getItemsSql,
param: new
{
Id = id
});
var idFromDb = (await reader.ReadAsync<int?>().ConfigureAwait(false)).SingleOrDefault();
if (idFromDb == null)
{
return null;
}
var items = await reader.ReadAsync<Item>(buffered: false).ConfigureAwait(false);
return Stream(reader, items);
}
private IAsyncEnumerable<Item> Stream(SqlMapper.GridReader reader, IEnumerable<Item> items)
{
using (reader)
{
await foreach (var item in items.ToAsyncEnumerable())
{
yield return item;
}
}
}
public async Task<IActionResult> GetItems(int id)
{
var items = await _query.GetItems(id);
return Ok(Stream(items);
}
private IAsyncEnumerable<ItemDto> Stream(IAsyncEnumerable<Item> items)
{
await foreach (var item in items)
{
yield return GetItemDto(item);
}
}
private static ItemDto GetItemDto(Item item)
{
return new ItemDto
{
// Convert Item to ItemDto
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment