【问题标题】:IDataRecord reader gets closed when calling Linq.First()IDataRecord 读取器在调用 Linq.First() 时被关闭
【发布时间】:2018-07-13 10:50:45
【问题描述】:

对于这样一段运行良好的代码 -

foreach (var dataRecord in dataRecords)
{
    return dataRecord.GetDateTime("MaxLogDate");
}

我尝试将其替换为

return dataRecords.First().GetDateTime("MaxLogDate");

但我得到了-

System.InvalidOperationException: 'Invalid attempt to call MetaData when the reader is closed.'

您能否指导我关闭此阅读器的原因和时间?

【问题讨论】:

  • 在获得第一之前转换ToList()怎么样?我想它是一种 interator 类型,所以迭代在对象内部做一些事情来打开阅读器
  • 什么是dataRecords,你是怎么得到它的?
  • 你知道这总是只返回第一条记录的数据吗?
  • 我只想要第一条记录数据
  • 转换为列表会引发同样的问题

标签: c# sql linq datareader


【解决方案1】:

这是如何使用它:

while(dataRecords.Read()){
    return dataRecords["columnName"].GetDateTime("MaxLogDate");
}

【讨论】:

  • 是的,我明白了,但问题是我只需要先返回,所以需要在循环中运行它似乎是多余的
  • 如果返回运行在第一个数据上,它不会循环任何内容lol
  • 如果您查看我的代码,我确实做到了这一点,但我想了解为什么 .first 不起作用
  • @MarcoSalerno OP 被while 弄糊涂了,你说必须完成循环让他们更加困惑。循环(while)一定不能完成,Read() 必须。您可以在没有循环的情况下调用一次Read。你最终会调用一次Read(),因为你从循环中return,但如果打算调用它一次,那么避免循环可能更具可读性。
  • 不,但它会更清楚地传达您的意图。 if (dataRecords.Read()) { return dataRecords["columnName"].GetDateTime("MaxLogDate"); }while(dataRecords.Read()) { return dataRecords["columnName"].GetDateTime("MaxLogDate"); } 更容易理解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多