TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Nullable Types Not Supported in ADO.NET = L-A-M-E

Maybe I'm the last person in the world to figure this out the hard way, but I'm probably not so hopefully this post helps someone out...

Don't try to use Nullable Types as SqlParameter values because they are not supported. You will end up with a nice little exception that says, “No mapping exists from object type System.Nullable...” I used “L-A-M-E” in my post title because IMO this has got to be THE TOP reason for having nullable types. Don't agree? Let's hear what Anders Hejlsberg has to say. Here's a code example if you aren't familiar with what I'm talking about...

string sql = @"insert into CustomerDemographics(CustomerTypeID, CustomerDesc, SomeIntColumn, SomeBitColumn, SomeDateColumn)

                values (@CustomerTypeID, @CustomerDesc, @SomeIntColumn, @SomeBitColumn, @SomeDateColumn)";

 

string customerTypeId = "test";

string customerDesc = "desc";

int? i = null;

bool? bb = null;

DateTime? dt = null;

 

using (SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["Main.ConnectionString"]))

using (SqlCommand command = new SqlCommand(sql, connection))

{

    connection.Open();

    command.Parameters.Add(new SqlParameter("@CustomerTypeID", customerTypeId));

    command.Parameters.Add(new SqlParameter("@CustomerDesc", customerDesc));

    command.Parameters.Add(new SqlParameter("@SomeIntColumn", i));

    command.Parameters.Add(new SqlParameter("@SomeBitColumn", bb));

    command.Parameters.Add(new SqlParameter("@SomeDateColumn", dt));

    command.ExecuteNonQuery();

}

 

 


Digg!

posted on Saturday, September 10, 2005 10:44 AM

Feedback

# re: Nullable Types Not Supported in ADO.NET = L-A-M-E 9/20/2005 7:46 AM David Browne

Try this again with the September CTP, aka RC0.

There has been a change in how nullable types are boxed. int? no longer boxes as a int?, instead it is boxed as an int or a null.

http://msdn2.microsoft.com/en-us/library/ms134802

Among other things this makes your example work.

David