0

请看下面的代码:

'Form1.vb
Imports System.Data.SqlClient

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'ExecuteDataReader(Function(x) New Person With {.URN = x("URN")})
        Try
            Dim results As IEnumerable(Of Person) = ExecuteDataReader(Function(x) New Person With {.URN = x("URN")})
            For Each c As Person In results 'Line 4
            Next
        Catch ex As Exception

        Finally

        End Try

    End Sub

    Public Function ExecuteDataReader(ByVal castRow As Func(Of IDataRecord, Person)) As IEnumerable(Of Person)
        Try
            Dim objCon As New SqlConnection("Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True")
            Dim objCommand As New SqlCommand
            Dim objDR As SqlDataReader
            objCon.Open()
            objCommand.Connection = objCon
            objCommand.CommandText = "SELECT URN FROM Person"
            objDR = objCommand.ExecuteReader()
            Do While objDR.Read
                castRow(objDR)
            Loop
        Catch ex As Exception

        End Try

    End Function
End Class

'Person.vb
Public Class Person
    'Implements IEnumerator, IEnumerable
    Public URN As String
End Class

为什么第 4 行的结果变量为空。我是 IEnumberators 的新手。我使用的 .NET 版本 (3.5) 不允许使用 Yield 关键字。

更新 Damien_The_Unbeliever 已更正代码。你认为这种模式适合数据逻辑层吗?我相信我有四个选择:

1) 将数据表而不是数据读取器返回到业务逻辑层。然后我可以将代码包装在 Using 语句中。
2)使用 Damien_The_Unbeliever 的答案中描述的模式将数据读取器返回到业务逻辑层(不在 Using 语句中包装一次性对象)。
3) 将数据读取器返回到业务对象层,并且仅在关闭数据读取器时关闭连接,即dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
4) 没有数据访问层。在需要时打开和关闭业务逻辑层中的连接。我相信这会降低代码的可维护性。

如果还有其他选择,请告诉我。

4

1 回答 1

2

试试这个:

Public Function ExecuteDataReader(ByVal castRow As Func(Of IDataRecord, Person)) As IEnumerable(Of Person)
    Using objCon As New SqlConnection("Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True")
      Using objCommand as New SqlCommand("SELECT URN FROM Person",objCon)
        Dim objDR As SqlDataReader
        objCon.Open()
        objDR = objCommand.ExecuteReader()
        Dim ret as New List(Of Person)
        Do While objDR.Read
            ret.Add(castRow(objDR))
        Loop
        Return ret
      End Using
    End Using
End Function

其中a)删除了“错误处理”的坏例子,它默默地吞下错误,b)包装SqlCommandSqlConnection对象,以便它们得到正确处理,以及c)实际上从函数返回一些东西,这是你出错的地方。

于 2012-11-18T13:41:01.620 回答