我有一个遗留应用程序,它包含一个数据库帮助程序类。客户端调用以下函数:
Public Overloads Shared Function ExecuteReader(ByVal connection As DbConnection, _
ByVal commandType As CommandType, _
ByVal commandText As String, _
ByVal ParamArray commandParameters() As DbParameter) As DbDataReader
' Pass through the call to private overload using a null transaction value
Return ExecuteReader(connection, CType(Nothing, DbTransaction), commandType, commandText, commandParameters, dbConnectionOwnership.External)
End Function
正如您所看到的,上面的函数调用了一个重载的ExecuteReader,它在下面详细说明:
Private Overloads Shared Function ExecuteReader(ByVal connection As DbConnection, _
ByVal transaction As DbTransaction, _
ByVal commandType As CommandType, _
ByVal commandText As String, _
ByVal commandParameters() As DbParameter, _
ByVal connectionOwnership As dbConnectionOwnership) As DbDataReader
If (connection Is Nothing) Then Throw New ArgumentNullException("connection")
Dim mustCloseConnection As Boolean = False
Dim cmd As DbCommand
' Create a command and prepare it for execution
If TypeOf (connection) Is SqlConnection Then
cmd = New SqlCommand
ElseIf TypeOf (connection) Is OracleConnection Then
cmd = New OracleCommand
End If
Try
' Create a reader
Dim dataReader As DbDataReader
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, mustCloseConnection)
' Call ExecuteReader with the appropriate CommandBehavior
If connectionOwnership = dbConnectionOwnership.External Then
dataReader = cmd.ExecuteReader()
Else
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
End If
' Detach the SqlParameters from the command object, so they can be used again
Dim canClear As Boolean = True
Dim commandParameter As DbParameter
For Each commandParameter In cmd.Parameters
If commandParameter.Direction <> ParameterDirection.Input Then
canClear = False
End If
Next
If (canClear) Then cmd.Parameters.Clear()
Return dataReader
Catch
If (mustCloseConnection) Then connection.Close()
Throw
End Try
End Function
我没有看到设置CommandTimeout属性的方法,而没有显着重构代码。从客户端多次调用此函数 - 只有一种情况需要更改commandtimeout。我有一些简单的想法:
1)将commandtimeout设置为实例变量(它不是静态的 类)。这似乎不正确。
2)使用可选 参数的默认值为:30。
还有其他方法吗?
我意识到我可能应该使用ORM,但这是一个遗留应用程序。
答案 0 :(得分:0)
我会使用可选参数,但不使用30
秒的硬编码默认值,而是使用默认值-1
并添加额外的if
语句以检查是否具体提供了值,如果应该覆盖默认超时。
通过这种方式,您仍然可以在连接字符串中设置默认超时,并在需要时使用特定的超时。