TVP - 无法将参数值从SqlParameter转换为IEnumerable`1

时间:2014-04-22 11:07:29

标签: asp.net vb.net sql-server-2008

我正在尝试创建一个可以接受tvp的通用功能。

我收到错误'无法将参数值从SqlParameter转换为IEnumerable`1。'

Dim param As New SqlParameter("@parName", GetTVP(lstDates))
param.SqlDbType = SqlDbType.Structured
sqlProvider.ExecuteNonQueryV2("sp_Save", CommandType.StoredProcedure, param)

                          ---------------------
Public Function ExecuteNonQuery(ByVal spname As String, ByRef returnValue As Integer, ByVal  ParamArray parameterValues() As Object) As Integer

    Dim connection As SqlConnection = Nothing
    Dim transaction As SqlTransaction = Nothing
    Dim command As SqlCommand = Nothing
    Dim r As Integer = -1

    Try

        connection = New SqlConnection(myconnectionString)
        command = New SqlCommand(spname, connection)
        command.CommandType = CommandType.StoredProcedure
        connection.Open()
        SqlCommandBuilder.DeriveParameters(command)
        Me.SetParameters(command, parameterValues)
        transaction = connection.BeginTransaction()
        command.Transaction = transaction
        r = command.ExecuteNonQuery()
        transaction.Commit()

    Catch ex As Exception

    Finally

    End Try

    Return r

End Function
                          ---------------------

Private Sub SetParameters(ByVal cmd As SqlCommand, ByVal parameterValues() As Object)
    Dim i As Integer
    For Each param As SqlParameter In cmd.Parameters
        param.Value = parameterValues(i)
        i += 1
    Next
End Sub

ADDED

我已更新代码并采用" SqlCommandBuilder.DeriveParameters(命令)" out和现在将参数作为sqlparameter列表传递。现在一切正常了:)

但我想知道为什么在我没有将参数类型定义为SqlDbType.Structured时它是否正常工作?它不是必需的吗?

Dim par As New List(Of SqlParameter)
par.Add(New SqlParameter("@parName", GetTVP(lstDates))

---------------

  connection = New SqlConnection(myconnectionString)
  command = New SqlCommand(spname, connection)
  command.CommandType = CommandType.StoredProcedure
  connection.Open()
  Me.SetParameters(command, parameterValues)
  transaction = connection.BeginTransaction()
  command.Transaction = transaction
  r = command.ExecuteNonQuery()
  transaction.Commit()

1 个答案:

答案 0 :(得分:0)

为什么不通过签名传递SqlParameter列表而不是参数列表作为参数?

你可以这样做;

Public Function ExecuteNonQuery(ByVal spname As String, 
                                ByRef returnValue As Integer, 
                                ByRef parameters As List(Of SqlParameter)) As Integer

然后你可以循环并添加

    For Each para As SqlParameter In parameters
        command.Parameters.Add(para)
    Next

检查此链接http://geekswithblogs.net/Rhames/archive/2008/10/29/why-you-should-always-specify-the-sqldbtype-for-an-ado.net.aspx。理想情况下,建议您定义参数类型,但这不是必需的。