问题
We have recently migrated our ASP.NET Core API which uses Dapper
to .NET Core 3.1. After the migration, we felt there was an opportunity to use the latest IAsyncEnumerable
feature from C# 8
for one of our endpoints.
Here is the pseudocode before the changes:
public async Task<IEnumerable<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 IEnumerable<Item> Stream(SqlMapper.GridReader reader, IEnumerable<Item> items)
{
using (reader)
{
foreach (var item in items)
{
yield return item;
}
}
}
After IAsyncEnumerable
code changes:
// Import Nuget pacakage: 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;
}
}
}
The above approach is to use ToAsyncEnumerable
is loosely inspired from this post, but I'm not 100% sure if I'm using it in the right place/ context.
Question:
- The dapper library only returns
IEnumerable
but can we useToAsyncEnumerable
to convert it intoIAsyncEnumerable
forasync
stream
like above?
Note: This question looks similar to What happens with returning IEnumerable if used with async/await (streaming data from SQL Server with Dapper)? but I do not think that answers my question.
来源:https://stackoverflow.com/questions/59956623/using-iasyncenumerable-with-dapper