【发布时间】:2020-07-11 10:49:38
【问题描述】:
我正在尝试返回一个 HTTP 响应,其中包含我从数据库中选择的记录数组。但我无法将我的IDataReader 映射到Enumerable。这是我的代码中相关的部分:
namespace Web.Api.Controllers
{
public static class Blah
{
public static IEnumerable<T> Select<T>(this IDataReader reader,
Func<IDataReader, T> projection)
{
while (reader.Read())
{
yield return projection(reader);
}
}
}
[HttpPost]
[Route("Search")]
public async Task<Tuple<int, IEnumerable<CustomerViewModel>, int>> Search([FromBody]CustomerViewModel model)
{
var s = _configuration.GetConnectionString("DefaultConnectionAlt");
using (SqlConnection connection = new SqlConnection(s))
{
connection.Open();
using (SqlCommand command = new SqlCommand("Search @RegistrationDate=\"2020-07-09\"", connection))
{
using (IDataReader reader = command.ExecuteReader())
{
var results = reader.Select<CustomerViewModel>(CustomerViewModel.Create);
return Tuple.Create(0, results, 29);
}
}
}
}
}
当我向http://localhost:42432/api/Search 发送 POST 请求时,while (reader.Read()) 行给出了错误:
System.InvalidOperationException: 'Invalid attempt to call Read when reader is closed.'
我在return Tuple.Create(0, results, 29); 放置了一个断点,当我检查results 变量时,它显示了我期望的结果。但是在我跳出那个断点之后,我在while (reader.Read()) 上得到了错误。
谁能告诉我如何解决我的问题?
我正在关注此处列出的示例:
How can I easily convert DataReader to List<T>?
Convert rows from a data reader into typed results
编辑 - 我正在使用 dotnetcore
【问题讨论】:
-
请说明您使用的 skd 版本(.net framework 还是 dot net core)?
-
@NicklausBrain 我编辑了我的问题,说我正在使用 dot net core
标签: c# idatareader