Hi,
I wrote my own database handling code (actually, I write T4 text templating files that generate my database code for me) and part of it takes care of converting values from a database (as Objects) to the desired types.
I have been using this generic function successfully:
It takes a type parameter (the type to convert to) and an Object (the value from the database), then checks if the value is null or DBNull, and if not the value is casted to type T.vb.net Code:
Public Overridable Function ConvertType(Of T)(value As Object) As T Try Return If(value IsNot Nothing AndAlso value <> DBNull.Value, DirectCast(value, T), Nothing) Catch ex As Exception Throw New ConversionException(GetType(T).Name, value.[GetType]().Name, ex) End Try End Function
Recently I have been adding support for SQL Server and SQLite (it used to be just MS Access) and I now need to handle Booleans as a special case. For SQLite for example, there is no boolean field so you generally use just an integer field, where 0 means False and 1 means True.
When I use my existing ConvertType method however, I will be trying to cast '1' or '0' to a Boolean, which will fail.
So, I can override this method for specific databases (Access doesn't override it as the default works, but SQLiteDatabase for example has to override it) and handle a Boolean value differently.
The idea is simply: if the type T is a Boolean and the value is an Integer, then I am assuming the database is storing an integer that represents a boolean. So, if the value is 1 I return True, if it's 0 I return False:
vb.net Code:
Public Overrides Function ConvertType(Of T)(value As Object) As T If GetType(T) Is GetType(Boolean) AndAlso TypeOf value Is Integer Then 'Special case If CInt(value) = 1 Then Return True Else Return False End If Else 'Handle as usual Return MyBase.ConvertType(Of T)(value) End If End Function
Simple enough, but it doesn't work... The return type of the function is (and must be) T, so I cannot return a Boolean because a Boolean cannot be converted to T!
Well... It can in this case, because I specifically check that T is Boolean, but the compiler doesn't know this so it doesn't allow me to return a Boolean. I cannot cast the boolean to T either.
Any idea's how I can solve this? I might be thinking too complex but I cannot see any solution![]()




Reply With Quote