I am interacting with a set of custom .Net 2.0 assemblies, with Powershell 2.0, to automate a current task. I load all the required dlls and call a DAL method, in the dll, to retrieve a System.Data.SqlDataReader. When I pass the SqlDataReader into a constructor in the same custom assembly I receive a "Invalid attempt to call HasRows when reader is closed." exception.
Code sample:
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)
The $reader is open, and has data, before I call the Thing constructor.
I must be missing something, but I am not sure what it is.
Edit 1:
$reader appears to be read, and closed, anytime it is passed to a function, in powershell or in an assembly. Is there a way to prevent this?
Edit 2:
Powershell automatic unrolling strikes again
How to stop PowerShell from unpacking an Enumerable object?
Strange behavior in PowerShell function returning DataSet/DataTable
The following modified code sample works by wrapping the result in a single element array, so the automatic unrolling does not affect the SqlDataReader. Note the single comma after the "$reader=" statement. That is not a typo.
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)