LINQ在bigint上引发无效的强制转换异常
我有一个看起来像这样的LINQ查询:
I have a LINQ query that looks something like this:
var clintLst = (from clntDt in ent.ClientDatas
where clntDt.CompanyName.Substring(0,searchWord.Length).Equals(searchWord, StringComparison.CurrentCultureIgnoreCase)
orderby clntDt.CompanyName
select new { ClientDataID = clntDt.ClientDataID,
CompanyName = clntDt.CompanyName,
ContactName = (clntDt.ContactFirstName + " " + clntDt.ContactLastName),
CompanyLocation = clntDt.Location.LocationCity.CityName + ", " + clntDt.Location.LocationState.StateCode
} ).Distinct().Take(10);
但是,它引发了以下异常:
However, it is throwing the following exception:
从物化的指定演员 将'System.Int32'类型键入 'System.Int64'类型无效. [..] 异常详细信息: System.InvalidOperationException: 从物化指定铸造 将'System.Int32'类型键入 "System.Int64"类型无效.
The specified cast from a materialized 'System.Int32' type to the 'System.Int64' type is not valid. [..] Exception Details: System.InvalidOperationException: The specified cast from a materialized 'System.Int32' type to the 'System.Int64' type is not valid.
源文件: C:\ TempPersonalCode \ TransportTracking \ TransportTracking \ TransportTracking \ Controllers \ AJAXController.cs 行:35
Source File: C:\TempPersonalCode\TransportTracking\TransportTracking\TransportTracking\Controllers\AJAXController.cs Line: 35
(第35行是select子句)
(Line 35 is the select clause)
我很困惑,因为如果更改:
I'm confused because if change:
select new { ClientDataID = clntDt.ClientDataID,
CompanyName = clntDt.CompanyName,
到
select new { ClientDataID = (Int32)clntDt.ClientDataID,
CompanyName = clntDt.CompanyName,
然后正常工作.匿名对象不应该使用反射来确定其类型吗?如果是这样,为什么要确定它是"Int32"而不是long?在EDMX中,我将其作为Int64.
then it works fine. Isn't an anonymous object supposed to use reflection to determine it's type? if so, why is it deciding that it's an "Int32" instead of a long? Within the EDMX I have it as an Int64.
短语物化值"是指从数据存储中检索到的值.
The phrase "materialized value" refers to the value that was retrieved from the data store.
可能发生的情况是数据库已将该列配置为int
,但是在您的EDMX文件中,该列是long
(或Int64
).
What's probably happening is that the database has that column configured as an int
, but in your EDMX file it's a long
(or Int64
).
您放在最前面的(Int32)
演员表正在(可能)被转换为数据存储(在SQL Server中,这意味着类似CAST([columnName] AS int)
的东西,因此,实体框架现在正在 以获得int
而不是long
.
The (Int32)
cast you're putting on the front is (probably) being translated to the data store (in SQL Server, this means something like CAST([columnName] AS int)
, and consequently, the Entity Framework is now expecting to get an int
instead of a long
.
如果不进行强制转换,则期望使用long
但获得int
.
Without the cast, it's expecting a long
but getting an int
.
解决方案是更改EDMX文件或更改列,以使EDMX文件中的数据类型与数据库中的数据类型匹配.
The solution is to either change the EDMX file or change the column, so that the data type in the EDMX file matches the data type in the database.
(jhott)