指定的强制转换是无效的Linq查询

您好我想基于其主键查询表。

我试过了两个

var deviceDetails = (from d in db.Devices where d.DeviceId == pointDetails.DeviceId select d).ToList(); 

编辑d.DeviceId

 var deviceDetails = db.Devices.Single(d => d.DeviceId == pointDetails.DeviceId) 

我知道这些会返回不同的类型,但现在这不是问题。

这个语句抛出一个invalidCastException,我不知道为什么。 PointDetails.DeviceId绝对是一个有效的int。 即使我用硬编码的int替换它,也会引发exception。

这是堆栈跟踪的相关部分。

  at System.Data.SqlClient.SqlBuffer.get_Int32() at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i) at Read_Device(ObjectMaterializer`1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) 

任何帮助都是因为我没有想法。

类定义和模式这是Device的类定义

 [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Devices")] public partial class Device : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _DeviceId; private int _DeviceTypeId; private string _DeviceName; private string _DeviceMACAddress; private string _DeviceIPAddress; private string _DeviceSubnetMask; private string _DeviceGatewayAddress; private int _ZoneId; private int _TelevisionTypeId; private int _DeviceStatusId; private byte _DeviceIsModified; private int _DeviceSetupBaudRate; private int _DeviceConfigId; private byte _DeviceSetupIsInputInternalPower; private int _DeviceBedSensorInput; private int _DeviceEnsuiteSensorInput; private int _DeviceRoomSensorInput; private string _DeviceSetupString1; private string _DeviceSetupString2; private string _DeviceSetupString3; private string _DeviceSetupString4; private byte _DeviceSetupIsWiegand; private int _DeviceSetupOptionId; private byte _DeviceSetupIsLightMomentary; private string _DeviceTestDateTime; private string _DeviceTestResults; 

这是SQL设计

SQL设计架构

编辑识别导致故障的列

我一次选择了一个colmun来找到导致转换exception的一个colmun,它是DeviceStatusId。 对SQL中的tinyInt类型有什么限制? 任何建议使这个正确投射

我认为错误不一定在你的where谓词中,而是在你的select (至少是间接的)。 数据库中的列(不一定是DeviceId列)可能与编译的C#代码中的属性不同。 它可以像一个可以为空的列(并且在某处包含空值)一样简单,其中代码的属性不可为空。

请注意exception发生的位置。 这一行表明它是在枚举结果时,而不是在评估where子句时(对“ToList”的调用):

 System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) 

这一行表明它是在构造实例时(或者更确切地说,当“对象”被“物化”时):

 Read_Device(ObjectMaterializer`1 ) 

就像这个(对构造函数的调用):

 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) 

基本上,至少有一列与代码不匹配,至少有一条记录利用了这种差异。 当发生这种情况时,正在构建的对象的构造函数会抛出exception,因为它无法理解它正在接收的数据。