0

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:

  1. Linq2SQL. Using a local data source will produce the expected cast exception
  2. 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.

waldrumpus
  • 2,540
  • 18
  • 44

2 Answers2

2

No cast exception occurs because the casts are sent into the database where they are performed by rules outside of .net.

It's the same reason this method doesn't throw.

It's the same reason that string comparison in a query is (by default) case-insensitive.

Community
  • 1
  • 1
Amy B
  • 108,202
  • 21
  • 135
  • 185
  • I accept this answer, because it must be the Linq2Sql query generation that changes the semantics of the expression. – waldrumpus Jul 11 '12 at 11:07
0
NorthwindDataContext db = new NorthwindDataContext();
IEnumerable<int> q =
  from x in db.Categories
  select x.CategoryID;

int[] ouch = q.ToArray();
Boomer
  • 1,468
  • 1
  • 15
  • 19
  • 2
    Please add in readable text what was wrong and what you have changed to fix the problem the original poster had. Answers that consist of only a code block are not very useful. – Sumurai8 Aug 03 '18 at 10:13
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/206345) by showing _why_ this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Blue Aug 03 '18 at 13:44