tags:

views:

1041

answers:

2

I am a bit of a newbie when it comes to Linq to SQL but I hope you can help out. I've written the following Linq to SQL statement with Extension Methods:

Cedb.ClassEvents.Where(c => c.ClassID == 1).Select(c => c).Single()

Where Cedb is the Datacontext, ClassEvents is a table (for classes and events being held at a facility) and ClassID is a unique integer key.

This query runs fine in LinqPad (without Cedb). When it returns, it says that the return type is "ClassEvent". In Intellisense in Visual studio, it tells me that the return type of this query is ClassEvent (created in my data model). However, when I try to place the results in a variable:

var classEvent = Cedc.ClassEvents.Where(c.ClassID == 1).Select(c => c).Single();

then I get an error: InvalidCastException: Specified cast is not valid. The same thing happens if I use the "ClassEvent" class in place of the var. I'm new to this but this one seems like a true slam dunk rather than a bug. Is there something about the Single method that I don't know that is leading to the error? Any help would be appreciated!

+1  A: 

You don't need to do both a Select and a Single, in fact, you don't even need the Where, you can get away with (see http://msdn.microsoft.com/en-us/library/bb535118.aspx):

var classEvent = Cedc.ClassEvents.Single(c => c.ClassID == 1);

I'd also recommend against using Single unless you're 100% sure that the Func<T, bool> will always return a value, as if it doesn't return a value you will have an exception thrown. Better is using SingleOrDefault and doing a null check before interaction with the object (http://msdn.microsoft.com/en-us/library/bb549274.aspx)

Slace
Thank you! I started typing "and if anyone knows a simpler way..." because I remember a "10 Myths" article that explained something of the sort. However, I'd like to understand what everything does and not just go for a shortcut. Fortunately, you did both. Thanks again.
Mark Brittingham
+2  A: 

Slace - and any other interested parties. The cause of the "Invalid Cast Exception" error was a change in the underlying data model. A smallint field had been changed to bit. Thus, when the system tried to map the query results onto the "ClassEvent" data structure, the conflict between the model (which had not been updated) and the data table emerged.

Nonetheless, I do appreciate the answer!

Mark Brittingham