views:

133

answers:

1

I'm trying to genericize (if that's even a word) the following line of code:

oCmd.CreateParameter("@Date", SqlDbType.DateTime, updateDate > DateTime.MinValue ? updateDate : SqlDateTime.Null);

The first change is obviously SqlDbType.DateTime to just DbType.DateTime, what do I do with the SqlDateTime.Null?

If I change to:

oCmd.CreateParameter("@Date", DbType.DateTime, updateDate > DateTime.MinValue ? updateDate : null);

I get the nice little red squiggly telling me there's no implicit conversion between DateTime and null. I don't seem to be able to find a generic way of doing this - is it possible?

Because of incompatibility between the source of the updateDate parameter and this line of code, I can't just use updateDate:

oCmd.CreateParameter("@Date", DbType.DateTime, updateDate);

Quite often the date we receive from the calling code is outside the valid date range of SQL Server and it causes the command to fail. Consequently there has to be a check done - hence the reason for the inclusion of the ternary check.

The only way I can see to do it is to break out to multiple lines, but I'm hoping someone's got a trick up their sleeve so I can keep it as one line.

Cheers in advance

+2  A: 

Try this:

oCmd.CreateParameter("@Date", DbType.DateTime,
    updateDate > DateTime.MinValue ? (object)updateDate : DBNull.Value);
LukeH
Works like a charm, thanks
BenAlabaster