Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DBNull.Value with SqlParameter without knowing sqlDbType?

I'm using a SqlParameter to pass in null values to a table for various columns that are nullable. The problem is that SqlParameter looks like it defaults to nvarchar if no sqlDbType is present. This presents a problem if the actual db type is varbinary; I get an exception saying

Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.

When I create the SqlParameter, all I know is the parameter's name, and object. If the object is null, SqlParameter obviously can't infer the right type to use, so is there a way to use SqlParameter with null values, without having to know the sqlDbType when creating the sql parameter?

Essentially pass the DBNull to the database without specifying the type, and let the database handle it?

like image 431
Alan Avatar asked Nov 19 '10 06:11

Alan


1 Answers

Old post but might be helpful someone else.

Convert.DBNull

Like this

command.Parameters.AddWithValue("@param", Convert.DBNull);
like image 75
Null Head Avatar answered Sep 29 '22 05:09

Null Head