Thursday, April 24, 2008

Specified Cast is Invalid using LINQ to SQL

I found a helpful troubleshooting option when debugging an error in some LINQ to SQL code.

I have a custom class in my designer called ActualHoursData and it has a few properties. This is not auto-generated from the designer but rather is used as a class to hold results from a method call to the database.

image

I have a simple ASP:Repeater on a Web Form bound to a LINQ to SQL method result that is essentially a collection of this class.

When I opened the Web form in a browser, I kept getting the "Specified Cast is Invalid" error, and the stack trace showed the error occurred during the databind.

I couldn't easily tell which column from the database was causing the issue, and as far as I could tell, the data types were correct. But I discovered that I can set each property's type to System.Object, instead of System.Decimal, and the code runs fine.

image

I was then able to revert each property's type back to the expected specific type, and I found which property that was really causing the problem.

No comments: