Jar*_*314 4 powershell sqldatareader powershell-2.0
我正在与一组使用Powershell 2.0的自定义.Net 2.0程序集进行交互,以自动执行当前任务.我加载所有必需的dll并在dll中调用DAL方法来检索System.Data.SqlDataReader.当我将SqlDataReader传递到同一个自定义程序集中的构造函数时,我收到"在读取器关闭时无效尝试调用HasRows".例外.
代码示例:
dir D:\stuff\*.dll | foreach { [Reflection.Assembly]::LoadFrom($_.FullName) } | out-null
[CustomAssembly.DataConfig]::ConnectionString = "Valid Connection String"
$reader=[CustomAssembly.DAL.Thing]::Get(123)
new-object CustomAssembly.BusinessObjects.Thing($reader)
Run Code Online (Sandbox Code Playgroud)
在我调用Thing构造函数之前,$ reader是打开的,并且有数据.
我必须遗漏一些东西,但我不确定它是什么.
编辑1:
$ reader在传递给函数,powershell或程序集中的任何时候似乎都被读取和关闭.有办法防止这种情况吗?
编辑2:
Powershell自动展开再次打击
如何阻止PowerShell解压缩Enumerable对象?
PowerShell函数中的奇怪行为返回DataSet/DataTable
以下修改的代码示例通过将结果包装在单个元素数组中来工作,因此自动展开不会影响SqlDataReader.请注意"$ reader ="语句后面的单个逗号.那不是拼写错误.
dir D:\stuff\*.dll | foreach { [Reflection.Assembly]::LoadFrom($_.FullName) } | out-null
[CustomAssembly.DataConfig]::ConnectionString = "Valid Connection String"
$reader=,[CustomAssembly.DAL.Thing]::Get(123)
new-object CustomAssembly.BusinessObjects.Thing($reader)
Run Code Online (Sandbox Code Playgroud)
我前段时间遇到过类似的问题.看看这段代码:
我创建了自己的Enumerator,它打印了一些关于何时调用它的信息.它与你的SqlDataReader(我认为)实现的IEnumerator一样.
PS> Add-Type -TypeDefinition @"
using System;
using System.Collections;
public class MyEnumerator2 : IEnumerator
{
private int _count = 10;
private Random r = new Random();
public MyEnumerator2(int count)
{
_count = count;
}
public bool MoveNext()
{
Console.WriteLine("Moving!");
_count--;
return _count >= 0;
}
public void Reset()
{
throw new NotImplementedException();
}
public object Current
{
get
{
Console.WriteLine("Current!");
return r.Next();
}
}
}
"@
Run Code Online (Sandbox Code Playgroud)
然后让我们创建一个类型的对象并尝试输出它:
PS> $mye = New-Object MyEnumerator2 5
PS> $mye | % -begin { write-host 'starting' } -Process { write-host 'next is ' $_ }
starting
Moving!
Current!
next is 2081278528
Moving!
Current!
next is 2000135673
Moving!
Current!
next is 692162542
Moving!
Current!
next is 1531746038
Moving!
Current!
next is 1550381634
Moving!
Run Code Online (Sandbox Code Playgroud)
一切都如预期.但现在
PS> function iteratemye($o) {
$o | % -begin { write-host 'starting' } -Process { write-host 'next is ' $_ }
}
PS> $mye = New-Object MyEnumerator2 5
PS> iteratemye $mye
Moving!
Current!
Moving!
Current!
Moving!
Current!
Moving!
Current!
Moving!
Current!
Moving!
starting
Moving!
Run Code Online (Sandbox Code Playgroud)
如果将此枚举器传递给函数,则会在它到达正文之前将其读取.那太糟糕了.
所以看看你的代码.如果你使用像我iteratemye这样的功能,那就是问题的原因.
更新:它没有实现IEnumerator,但是IEnumerable.我看到你只是将对象传递给一些构造函数,这与我遇到的问题不同,但我相信PowerShell仍会尝试获取枚举器并做一些魔术.
| 归档时间: |
|
| 查看次数: |
1249 次 |
| 最近记录: |