Thursday, 16 September 2010

ASP.NET: InvalidCastException from Strongly-Typed DataSet (XSD)

This one has had me tearing my hair out for months.

In most of my ASP.NET projects I would have an XSD DataSet which models my database schema and acts as the data access layer for the application. But in several situations I would get unbelievably annoying exceptions from the designer file whenever my code attempted to get a boolean or date value from the database which was null. You would receive an exception like this:

StrongTypingException was unhandled by user code.

The value for column 'abcdefgh' in table 'tblAbcdef' is null.

My first step was to open the Properties of the column in the XSD designer and make sure that the AllowDbNull property is set to true. Then in the NullValue property I tried to change the behaviour from (Throw exception) to (Empty) or (Nothing). But Visual Studio blew up in my face and informed me that my selection was invalid.

'Fine' I thought, 'I'll just check the value for DbNull before trying to set it in my code'. But when I tried to do such an IF statement, the StrongTypingException would still occur because before my expression tried to evaluate the column value, the designer would throw the StrongTypingException, thus never allowing the evaluation to take place.

I couldn't find the answer to this, until a much smarter colleague pointed out the extremely simple answer. The designer file catches a InvalidCastException and then throws a StrongTypingException. So in my own code, I just need to catch the StrongTypingException and ignore it - assuming that ignoring it is the correct thing to do in that piece of code. I had been trying to catch the InvalidCastException which of course is incorrect because the designer had replaced that with the other exception type.

.ClientContact = dbRecord.ClientIsStudent
Catch ex As Global.System.Data.StrongTypingException
' Ignore since these are generated from the typed DataSet designer
End Try

This worked and I am delighted to finally have the answer to this problem which has been bugging me for ages!

If I had actually read the designer file code I might have spotted that it throws a different type of exception to the one I was trying to catch.