简体   繁体   English

Linq2SQL查询中无法进行强制转换

[英]Invalid cast is possible in Linq2SQL query

I've had trouble with a Linq2SQL query. 我在使用Linq2SQL查询时遇到了麻烦。 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). CategoryID是一个int 。)最后, ouch将填充零(数据库中的每个类别为零)。 I have used int and ArrayList in this example; 我在这个例子中使用了intArrayList ; the exact types are irrelevant. 确切的类型是无关紧要的。 The main points needed to repeat this phenomenon are: 重复这一现象所需的要点是:

  1. Linq2SQL. 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. select表达式中使用查询的数据库表的属性。 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 ? 我的问题是,为什么上面的代码不会产生异常试图将ArrayList转换为int

The generated SQL code according to LINQPad: 根据LINQPad生成的SQL代码:

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 . ChildClass继承自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. 仅当db是Linq2SQL连接时才会发生这种情况,而不是它是本地数据源。 Trying to understand the cause of this behavior led me to the code I posted above. 试图理解这种行为的原因导致我上面发布的代码。

No cast exception occurs because the casts are sent into the database where they are performed by rules outside of .net. 不会发生强制转换异常,因为强制转换被发送到数据库,在那里它们由.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. 这与查询中的字符串比较(默认情况下)不区分大小写的原因相同。

NorthwindDataContext db = new NorthwindDataContext();
IEnumerable<int> q =
  from x in db.Categories
  select x.CategoryID;

int[] ouch = q.ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM