Pap*_*ste 6 c# sql linq casting
您好我想基于其主键查询表.
我试过了两个
var deviceDetails = (from d in db.Devices
where d.DeviceId == pointDetails.DeviceId
select d).ToList();
Run Code Online (Sandbox Code Playgroud)
编辑d.DeviceId
var deviceDetails = db.Devices.Single(d => d.DeviceId == pointDetails.DeviceId)
Run Code Online (Sandbox Code Playgroud)
我知道这些会返回不同的类型,但现在这不是问题.
这个语句抛出一个invalidCastException,我不知道为什么.PointDetails.DeviceId绝对是一个有效的int.即使我用硬编码的int替换它,也会引发异常.
这是堆栈跟踪的相关部分.
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)
Run Code Online (Sandbox Code Playgroud)
任何帮助都是因为我没有想法.
类定义和模式 这是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;
Run Code Online (Sandbox Code Playgroud)
这是SQL设计
编辑识别导致故障的列
我一次选择了一个colmun来找到导致转换异常的一个colmun,它是DeviceStatusId.对SQL中的tinyInt类型有什么限制?任何建议使这个正确投射
Dav*_*vid 12
我认为错误不一定在您的where谓词中,而在您的select(至少是间接的)中.数据库中的DeviceId列(不一定是列)可能与编译的C#代码中的属性不同.它可以像一个可以为空的列(并且在某处包含空值)一样简单,其中代码的属性不可为空.
请注意异常发生的位置.这一行表明它是在枚举结果时,而不是在where评估子句时(对"ToList"的调用):
System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
Run Code Online (Sandbox Code Playgroud)
这一行表明它是在构造一个实例时(或者更确切地说,当"对象"被"物化"时):
Read_Device(ObjectMaterializer`1 )
Run Code Online (Sandbox Code Playgroud)
就像这个(对构造函数的调用):
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
Run Code Online (Sandbox Code Playgroud)
基本上,至少有一列与代码不匹配,至少有一列利用了这种差异.当发生这种情况时,正在构建的对象的构造函数会抛出异常,因为它无法理解它正在接收的数据.