I've had trouble with a Linq2SQL query. Dissection of the offending query yields this minimal example of its baffling behavior.
NorthwindDataContext db =
new NorthwindDataContext();
IEnumerable<int> q =
from x in db.Categories
select (int)(object)new System.Collections.ArrayList(x.CategoryID);
int[] ouch = q.ToArray();
(CategoryID
is an int
.) At the end, ouch
will be filled with zeroes (one zero for every category in the database). I have used int
and ArrayList
in this example; the exact types are irrelevant. The main points needed to repeat this phenomenon are:
- Linq2SQL. Using a local data source will produce the expected cast exception
- Use of a property of the queried database table in the
select
expression. If no column of the queried tables is used, a cast exception will be raised.
My question is, why doesn't the above code produce an exception trying to cast the ArrayList
into an int
?
The generated SQL code according to LINQPad:
SELECT NULL AS [EMPTY]
FROM [Categories] AS [t0]
As a background to my question: My original code read something like this:
IEnumerable<ParentClass> q =
(from x in db.SomeTable
select (ParentClass) new ChildClass { SomeProperty = x.SomeColumn })
.ToArray();
ChildClass
inherits from ParentClass
. This code though correctly typed and semantically sound, raises an exception. This happens only if db
is a Linq2SQL connection, not if it's a local data source. Trying to understand the cause of this behavior led me to the code I posted above.