Wednesday, 17 March 2010

SqlParameterCollection Extension Method AddWithValue

I don’t know why it’s not included in .net 3.5 / c#3 but the recommended way of adding a SQL Parameter to a SqlParameterCollection is to use the AddWithValue method; however, you can’t specify the SqlDbType with any of the overloads. It’s not hard …

    public static class DataAccessExtensions
{
/// <summary>
/// AddWithValue specifiying the <see cref="SqlDbType"/> of the parameter
/// </summary>
/// <param name="collection">The collection to add the parameter to</param>
/// <param name="parameterName">The name of the parameter</param>
/// <param name="value">The value of the parameter</param>
/// <param name="sqlDbType"><see cref="SqlDbType"/> which the SqlCommand is expecting for the created parameter</param>
public static void AddWithValue(this SqlParameterCollection collection, string parameterName, object value, SqlDbType sqlDbType)
{
var result
= new SqlParameter(parameterName, sqlDbType) { Value = value };
collection.Add(result);
}
}



No comments: