I don't think the error is necessarily in your where
predicate, but in your select
(at least indirectly). It's likely that a column in the database (not necessarily the DeviceId
column) is of a different type than a property in the compiled C# code. It could be as simple as a column being nullable (and containing a null value somewhere) where the code's property is not nullable.
Note where the exception is happening. This line suggests that it's when the results are enumerated, not when the where
clause is evaluated (the call to "ToList"):
System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
And this line suggests that it's when an instance is being constructed (or rather, when an "object" is being "materialized"):
Read_Device(ObjectMaterializer`1 )
As does this one (the call to the constructor):
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
Basically, there's at least one column that doesn't match the code and at least one record which takes advantage of that discrepancy. When that happens, the constructor for the object being built throws an exception, because it can't make sense of the data it's receiving.