Brandi
Brandi

Reputation: 1579

Open SqlConnection being passed as a parameter?

I ran across this bit of code (not mine) and it weirded me out a little bit.

Public Overridable Function Save(ByVal UpdateUserID As Integer) As Integer
    Dim conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("mcle").ToString())

    Try
        conn.Open()
        Return Save(conn, UpdateUserID)
    Finally
        conn.Close()
    End Try
End Function

Public Overridable Function Save(ByVal conn As SqlConnection, ByVal UpdateUserID As Integer) As Integer
    If Me.activityID <> 0 Then
        Return SaveAct(conn, UpdateUserID)
    Else
        Return AddAct(conn, UpdateUserID)
    End If
End Function

(For reference, SaveAct and AddAct are both long functions that add a bunch of parameters and update the database)

Now, is it kosher to pass the open connection as a parameter or could this lead to problems? Not breaking so far, just wondering what the best practice is here.

Thanks in advance.

Upvotes: 0

Views: 1236

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415665

Passing an open connection is perfectly okay to do... though normally I'd invert that and use a function that returns an open and ready connection into the existing function. So it might look something like this:

Public Overridable Function Save(ByVal UpdateUserID As Integer) As Integer
    Using cn As SqlConnection = GetConnection()
        If Me.activityID <> 0 Then
            Return SaveAct(conn, UpdateUserID)
        Else
            Return AddAct(conn, UpdateUserID)
        End If
    End Using
End Function

This code would be part of a data access layer, such that only certain methods/classes can see the GetConnection() method.

Upvotes: 2

Related Questions