指定的强制转换对RowNumber无效

时间:2014-08-24 06:45:41

标签: c# sql-server visual-studio-2010

我有这段代码

  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

我已将Row定义为整数,我将其作为Int32,所以为什么我收到此错误消息?

谢谢

1 个答案:

答案 0 :(得分:3)

你应该把它投长到

尝试将代码更改为

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

http://social.msdn.microsoft.com/forums/sqlserver/en-US/e3ced4f6-2514-4a1a-87d3-d19e4ccd6d63/rownumber-data-type

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