尝试将现有数据访问代码转换为异步并遇到 Rx,因为您无法在方法主体中返回Task<IEnumerable<T>>
a yield return
。
我写了这个,但不确定它是异步的,所以感激地收到了指针
public class EmployeeRepository : IEmployeeRepository
{
public IAsyncEnumerable<Employee> GetEmployees()
{
return Enumerable().ToAsyncEnumerable();
}
private IEnumerable<Employee> Enumerable()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ConnectionString))
{
connection.Open();
using (var command = new SqlCommand(@"SELECT * FROM EMPLOYEES", connection))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return
new Employee()
{
Id = ReadField<int>(reader, "Id"),
Name = ReadField<string>(reader, "Name")
};
}
}
}
}
}
private static T ReadField<T>(IDataRecord reader, string fieldName)
{
var value = reader[fieldName];
return value == DBNull.Value ? default(T) : (T)value;
}
}