[Mono-list] DBNull value causes InvalidCastException

Aleksey Demakov avd@openlinksw.com
Wed, 22 Jan 2003 01:24:50 +0600


This is a multi-part message in MIME format.
--------------020808060601060208030703
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit

Hi all,

While working with Virtuoso .NET data provider I run
across a case when filling a dataset with data from
a table produces InvalidCastException.

The investigation has shown that it was caused by the
following code fragment in the DataRow.cs:

> if (value[i] == null)
> {
> 	if (!_table.Columns[i].AllowDBNull)
> 		throw new NoNullAllowedException ();
> 	continue;
> }
> 					
> //FIXME: int strings can be converted to ints
> if (_table.Columns[i].DataType != value[i].GetType())
> 	throw new InvalidCastException ();

You can see that the code checks for null value
but not for DBNull. I'm not sure if null may
be used as DBNull. So perhaps the null check has to
be replaced DBNull check. However, I only added
the DBNull check for the existing one.

The patch is in the attached file.

BTW, for DBNull comparison I've used the following
construct:

   value[i] == DBNull.Value

I don't know if it is the most correct way. It might
be that a more correct way is something like

   Convert.IsDBNull (value[i])

The mono implementation of Convert.IsDBNull does
essentially the same, but I've taken a look into
rotor and its implementation of Convert.IsDBNull
returns true if value[i] is equal to DBNull.Value
OR if it is a IConvertible and IConvertible.GetTypeCode()
is equal to TypeCode.DBNull.

Regards,
Aleksey

--------------020808060601060208030703
Content-Type: text/plain;
 name="DataRow.cs.patch"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="DataRow.cs.patch"

Index: DataRow.cs
===================================================================
RCS file: /mono/mcs/class/System.Data/System.Data/DataRow.cs,v
retrieving revision 1.28
diff -u -r1.28 DataRow.cs
--- DataRow.cs	29 Dec 2002 14:50:14 -0000	1.28
+++ DataRow.cs	21 Jan 2003 10:04:51 -0000
@@ -246,7 +246,7 @@
 					if (_table.Columns[i].ReadOnly && value[i] != this[i])
 						throw new ReadOnlyException ();
 
-					if (value[i] == null)
+					if (value[i] == null || value[i] == DBNull.Value)
 					{
 						if (!_table.Columns[i].AllowDBNull)
 							throw new NoNullAllowedException ();

--------------020808060601060208030703--