+3  A: 

You may have changed something in your database (like datatype of a column) without remembering to re-create your LINQ classes. Thus LINQ to SQL may be causing that casting exception.

çağdaş
I'll look into that... don't think I did, but worth a look. Thank you!
Chad
+3  A: 

You haven't given nearly enough information to troubleshoot, and (no offense) I'm not heading over to YouTube to watch a video. Here are some general troubleshooting steps I'd take and questions I'd ask myself:

  1. When it fails, is it always the exact same exception? Or does it vary? If the same exception is always thrown then there might be a defect in your logic somewhere. If you get totally random exceptions then you may have a hardware or infrastructure issue.

  2. First thing to do when you get LINQ to SQL exceptions is hook up SQL Profiler to see the exact query statement being sent to the server. Copy/paste that into SQL Management Studio and run it by hand. Look at the results and compare them to the data types of the object you're loading: is the query mapping an empty value to a non-nullable field? Maybe a query column is being mapped to a property of a different type?

  3. If it works for 3-4 minutes, then stops for 3-4 minutes, then works again, look for any time-specific code in your project. Are you doing any caching? Maybe the issue is related to the behavior that occurs when the cache is stale versus when it's not stale, or vice versa. Maybe you have a date/time calculation that overflows or does something funky for certain inputs?

  4. Hook up a debugger and have it catch the exception. Then walk up the stack trace and look at the program state during a failure. Compare it to the program state when the app is working correctly. Anything stand out?

Seth Petry-Johnson
added more code to the question... going to see if I can reproduce the issue locally. Thanks.
Chad
I'm on to something... will post again if my quick change fixes things. Thanks for your advice!
Chad
@Chad: "Specified cast is not valid" indicates a data type mismatch between a row in the SQL result set and the object you're mapping it to. Do any of the integer or date/time DB columns allow null? If so, are they being mapped to nullable types in your object?
Seth Petry-Johnson
@Seth Petry-Johnson I was able to reproduce the problem locally. It appears the issue was caused when a certain method was attempting data access when the data connection was not open. This was possibly being caused by some IEnumerable iterations holding a connection open, then it attempting to be Disposed right before a late call for the data was attempted... exacerbated by latency between host and db server. Thanks for your common-sense troubleshooting reminder, got me back on track.
Chad