是一个静态方法,对于不同的调用使用相同的变量
我有这个方法:
public static IEnumerable<T> ExecuteReaderSp<T>(string sp, string cs, object parameters) where T : new()
{
using (var conn = new SqlConnection(cs))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sp;
cmd.InjectFrom<SetParamsValues>(parameters);
conn.Open();
using (var dr = cmd.ExecuteReader())
while (dr.Read())
{
var o = new T();
o.InjectFrom<ReaderInjection>(dr);
yield return o;
}
}
}
}
当我在 “事务范围” 内多次调用它(具有不同的 T 和 sp)
并且我没有调用 .ToArray()< 时, 我遇到了这种情况/code> 第一次调用时出现错误,告诉我此命令已与另一个 DataReader 关联,并且应首先关闭第一个
I have this method:
public static IEnumerable<T> ExecuteReaderSp<T>(string sp, string cs, object parameters) where T : new()
{
using (var conn = new SqlConnection(cs))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sp;
cmd.InjectFrom<SetParamsValues>(parameters);
conn.Open();
using (var dr = cmd.ExecuteReader())
while (dr.Read())
{
var o = new T();
o.InjectFrom<ReaderInjection>(dr);
yield return o;
}
}
}
}
I had the situation when I called it to times (with different T and sp) inside a "transaction scope"
and if I wasn't calling .ToArray()
on the fist call than I had an error that was telling me that this Command is already associated with another DataReader and that the first one should be closed first
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于它在事务范围内,我确信 ADO.Net 正在提供与数据库相同的物理连接,但我认为文本 this Command is已经关联 是红鲱鱼 - 尝试将
MultipleActiveResultSets=True
添加到您的连接字符串中。您在这里遇到的情况是,在完全遍历
IEnumerable
对象之前,具有yield return
的函数不会完全计算 - 并且 SqlConnections 默认情况下只允许一个 DataReader一次积极地对抗他们。另外,我对您正确使用 using 语句表示赞赏 - 但请注意,在您遍历整个
IEnumerable
之前,不会有任何内容被 Dispose。 (这就是ToArray()
正在为您做的事情,让一切正常工作。)Since it's in a transaction scope, I'm sure that ADO.Net is providing the same physical connection to the database, but I think the text this Command is already associated is a red herring - try adding
MultipleActiveResultSets=True
to your connection string.The situation you're running into here is functions with
yield return
aren't fully evaluated until theIEnumerable
objects are fully walked - and SqlConnections, by default, only allow one DataReader to be active against them at a time.Also, I applaud your proper use of using statements - but be aware that nothing will get Disposed until you walk the entire
IEnumerable
. (This is whatToArray()
is doing for you to make it all work.)