指定的类型转换对RowNumber无效

本文关键字:RowNumber 无效 类型转换 | 更新日期: 2023-09-27 18:19:11

我有这样的代码

  using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionStringName))
        {
            Helpers helpers = new Helpers();
            myConnection.ConnectionString = helpers.GetConnectionString(myUser.ServerName, myConnection.ConnectionString);
            using (SqlCommand myCommand = new SqlCommand("Select ROW_NUMBER() OVER(ORDER BY PersonelNo DESC) AS Row,* from View_Insurance", myConnection))
            {
                myConnection.Open();
                using (SqlDataReader myReader = myCommand.ExecuteReader())
                {                       
                    while (myReader.Read())
                    {
                        InsuranceEntities insuranceEntity = new InsuranceEntities();
                        insuranceEntity.Row = myReader.GetInt32(myReader.GetOrdinal("Row"));
                        insuranceEntity.Id = myReader.GetInt32(myReader.GetOrdinal("Id"));
                        insuranceEntities.Add(insuranceEntity);
                    }
                    myReader.Close();
                }
            }
            myConnection.Close();
        }

和实体:

  class InsuranceEntities
{
    public int Row { get; set; }
    public string FName{ get; set; }

    public InsuranceEntities()
    {
    }
    public InsuranceEntities(int row,string  fName)           
    {
        this.Row = row;
        this.FName= fName;           
    }  
}
但是当它到达 行时
   insuranceEntity.Row = myReader.GetInt32(myReader.GetOrdinal("Row"));

我得到以下错误

   Specified cast is not valid

我已经将行定义为整数,我得到的是Int32,所以为什么我得到这个错误信息?

谢谢

指定的类型转换对RowNumber无效

应该将其强制转换为long

尝试将代码更改为

//I guess , or similar 
insuranceEntity.Row = myReader.GetInt64(myReader.GetOrdinal("Row"));

http://social.msdn.microsoft.com/forums/sqlserver/en us/e3ced4f6 - 2514 - 4 - a1a - 87 - d3 - d19e4ccd6d63/rownumber -数据类型

http://msdn.microsoft.com/en-us/library/cc716729.aspx