In VB.NET, I am creating extension methods for the SqlParameterCollection class so that I can add “detailed” parameters in one line of code. I understand that the .AddWithValue method will cause SQL Server to re-evaluate an SQL Server execution plan each time a Stored Procedure is called via an SqlCommand with SqlParameter objects that do not specify the size of alphanumeric data types (i.e. VarChar or NVarChar). In other words, .AddWithValue is a bad idea except for types like INT data types where the size of the data type is constant.
I’ve never used Extension Methods before, so does this code appear to accomplish what I want? The code “works”, but I’m looking for another set of eyes to make sure I’m not ending up with parameters that will force re-evaluation of an SQL Server execution plan.
EDIT: I had to actually add the parameter to the “params” collection, so I’ve updated the code. Now it “works” 😉
Imports System.Runtime.CompilerServices
Public Module AdoParameterExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Sub AddWithNumericValue(ByVal params As System.Data.SqlClient.SqlParameterCollection, ByVal parameterName As String, ByVal parameterType As SqlDbType, ByVal value As Object)
Dim newParam As New System.Data.SqlClient.SqlParameter
With newParam
.ParameterName = parameterName
.SqlDbType = parameterType
.Value = value
End With
params.Add(newParam)
End Sub
<System.Runtime.CompilerServices.Extension()> _
Public Sub AddWithStringValue(ByVal params As System.Data.SqlClient.SqlParameterCollection, ByVal parameterName As String, ByVal parameterType As SqlDbType, ByVal size As Integer, ByVal value As Object)
Dim newParam As New System.Data.SqlClient.SqlParameter
With newParam
.ParameterName = parameterName
.SqlDbType = parameterType
.Size = size
.Value = value
End With
params.Add(newParam)
End Sub
End Module
Thanks for your feedback.
Your extensions look fine. Whether or not the SQL Server execution plan well be re-evaluated won’t be affected by using an Extension method.
One recommendation I’d make is to return the SqlParameterCollection instead of void (Sub). Parameters can then be added fluently.
Instead of
you write as
It’s a preference, but with extensions like this I’ve come to appreciate the style.