简体   繁体   中英

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)
};
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 .)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM