Pregunta

I have a global class setup as

Public Class ReqGlobal
  Private Shared _sqlConn As SqlClient.SqlConnection

  Public Shared Property SqlConnection As SqlClient.SqlConnection
    Get
        Return _sqlConn
    End Get
    Set(value As SqlClient.SqlConnection)
        _sqlConn = value
    End Set
  End Property

  Private Sub New()
    ' Prevents users from making this an instance
  End Sub
End Class

Then on my form I would run the following code:

Dim sqlConn as SqlConnection = ReqGlobal.SqlConnection
Using conn As SqlClient.SqlConnection = sqlConn 
            conn.Open()
            Using bulkCopy As SqlClient.SqlBulkCopy = New SqlClient.SqlBulkCopy(conn)
                bulkCopy.DestinationTableName = "tableName"

                bulkCopy.WriteToServer(dt)
            End Using
End Using

Now when it gets to End Using it clears the connection string in conn as it should, but it also is some how clearing the connection string in ReqGlobal.SqlConnection

Can someone explain what I am doing wrong here and why its clearing the connection string in both places, please. This is a Class Library if that matters.

¿Fue útil?

Solución

Since SqlConnection is a reference type, when you assign conn in the using statement the actual global connection is used and not a copy.
When the using scope ends Disposed is called on the global connection and it becomes useless. You should not use a global connection like this for thread safety issues (among others).

I would recommend either creating a new connection in the using statement with the connection string from the global class, or calling a method in the global class that creates the connection.

Public Class ReqGlobal
   private shared _cnnStr As string = "someConnectionString"

   Public Shared Function GetConnection() As DbConnection
      Dim con = new SqlClient.SqlConnection(_cnnStr)
      con.Open()
      return con
   End Function

End Class

Usage

Using conn As DbConnection = ReqGlobal.GetConnection()
...
End Using

Otros consejos

End Using calls the Dispose method on your global connection object, therefor you won't be able to use it afterwards.

Don't use a global connection. Instead, initialize the conneciton string on a global level and create a new SqlConnection object every time you want to execute a query:

Using connection = New SqlClient.SqlConnection(_connectionString)
    ' Your code
End Using
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top