C# ASP.NET MVC 4-指定的强制转换无效

C# ASP.NET MVC 4-指定的强制转换无效,c#,asp.net,C#,Asp.net,我有一个模型类,在顶部,我定义了这个int: public int AppForms { get; set; } 但当我试图从SQlDataReader向其分配数据时,我试图分配的值是1或0。我尝试了以下内容,得到了以下错误 airportItems.AppForms = dataReader.GetValue(26); Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are y

我有一个模型类,在顶部,我定义了这个int:

 public int AppForms { get; set; }
但当我试图从SQlDataReader向其分配数据时,我试图分配的值是1或0。我尝试了以下内容,得到了以下错误

airportItems.AppForms = dataReader.GetValue(26);
Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)

airportItems.AppForms = (int)dataReader.GetValue(26);
Specified cast is not valid.
我做错了什么

机场是

var airportItems = new AirportClass();
而dataReader是

SqlDataReader dataReader = command.ExecuteReader();
我试图设置的值在while循环中

while (dataReader.Read())

基于此,索引26处的项很可能不是int,或者实际上可能是null。在转换为int(null是DbNull类型)之前,必须首先检查null。您可以首先执行以下操作:

if (!dataReader.IsDBNUll(26))

要确保它不为null,请强制转换。

SqlDataReader.GetValue()
类型列返回一个
bool

请尝试:

public bool AppForms { get; set; }

airportItems.AppForms = !dataReader.IsDBNUll(26) && (bool)dataReader.GetValue(26);
或:


为了进行调试,请参阅
dataReader.GetValue(26).GetType()提供的内容。此外,按列索引获取值很难读取,使用列名会提高可读性。如果使用Convert.ToInt32(dataReader.GetValue(26))?@Matthew使用列索引可以显著提高大型紧密循环中的性能。但是,我会从循环外的列名中查找索引,并使用它,而不是硬编码索引号。
SqlDataReader.GetValue()
类型列返回一个
bool
public bool AppForms { get; set; }

airportItems.AppForms = !dataReader.IsDBNUll(26) && dataReader.GetBoolean(26);