Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way of providing SqlDbType?

I have this working code below. However, I there is no SqlParameter constructor that takes name, value, and SqlDbType and I want to just provide the type for the date parameters. Is there a way to do that which does not require adding a lot of code?

SqlParameter[] parameters =  
{
    new SqlParameter("@START_ORDER", startOrder),
    new SqlParameter("@END_ORDER", endOrder), 
    new SqlParameter("@START_ITEM", startItem), 
    new SqlParameter("@END_ITEM", endItem), 
    new SqlParameter("@START_DUEDATE", dateFrom), 
    new SqlParameter("@END_DUEDATE", dateTo)
};
like image 725
CodenameCain Avatar asked Mar 17 '23 00:03

CodenameCain


2 Answers

new SqlParameter("@name", SqlDbType.Whatever) { Value = value }

There are constructor overloads that take all kinds of parameters, but they are perhaps not worth the hassle of specifying each and every argument. The above is probably as simple as it gets.

(Note that in some cases you might want to set SqlValue instead of Value.)

like image 127
stakx - no longer contributing Avatar answered Mar 29 '23 05:03

stakx - no longer contributing


If you're doing a lot of manual ADO.NET, a good alternative might be to build a few helpers into a base class or utility class, which would also aid in ensuring you're passing in the right types:

public static SqlParameter CreateStringParam(string paramName,
    int length, string value) {}
public static SqlParameter CreateIntParam(string paramName,
    int? value) {}
// etc...

These helpers could help you out by converting null to DBNull.Value, and ensuring you remember about parameter size for strings and numbers.

At most you'd have to build a dozen or so, but more than likely you're only using a handful of data types, so you shouldn't need many of these.

like image 28
Joe Enos Avatar answered Mar 29 '23 04:03

Joe Enos