C# 如何从SqlDataReader获取int32和字符串。获取错误System.IndexAutoFrangeException:'StudentID'

C# 如何从SqlDataReader获取int32和字符串。获取错误System.IndexAutoFrangeException:'StudentID',c#,sql,asp.net,sql-server,C#,Sql,Asp.net,Sql Server,我正在从事一个个人项目,该项目使用Microsoft SQL DB和web层进行Rest API调用。我试图使用SqlDataReader从数据库中获取Int32和字符串。当我读取字符串时没有错误,但是当我尝试读取整数时,我得到以下结果 `异常:System.IndexOutOfRangeException:'StudentID' 公共学生帐户查找学生id { 使用SqlConnection=newsqlconnectionconnectionstring { 连接。打开; 字符串sql=从[P

我正在从事一个个人项目,该项目使用Microsoft SQL DB和web层进行Rest API调用。我试图使用SqlDataReader从数据库中获取Int32和字符串。当我读取字符串时没有错误,但是当我尝试读取整数时,我得到以下结果

`异常:System.IndexOutOfRangeException:'StudentID'

公共学生帐户查找学生id { 使用SqlConnection=newsqlconnectionconnectionstring { 连接。打开; 字符串sql=从[PersonTest].[dbo].[StudentAccounts]中选择FirstName、LastName、Student传记,其中StudentID=@p1; StudentAccount matchingStudent=新的StudentAccount; 使用SqlCommand cmd=newsqlcommandsql,连接 { cmd.Parameters。Add@p1,SqlDbType.Int.Value=id; cmd.CommandType=CommandType.Text; SqlDataReader=cmd.ExecuteReader; 边读边读 { matchingStudent.StudentID=reader.GetInt32reader.GetOrdinalStudentID; matchingStudent.FirstName=读取器[FirstName].ToString; matchingStudent.LastName=读取器[LastName].ToString; matchingStudent.传记=读者[学生传记].ToString; matchingStudent.CollegeID=reader.GetInt32reader.GetOrdinalCallTB_CollegeID; } 读者。关闭; 还匹配学生; } } } 学生帐户表如下所示:

StudentAccounts (StudentID, FirstName, LastName, StudentBiography, CollTB_CollegeID)
学生ID是主键

我提前道歉,如果我弄乱了格式或任何东西,这是我第一次在这个论坛上发布。谢谢

您正在使用:

matchingStudent.CollegeID = reader.GetInt32(reader.GetOrdinal("StudentID"));
这意味着:

var columnNumber = reader.GetOrdinal("StudentID");
matchingStudent.CollegeID = reader.GetInt32(columnNumber);
现在第一个调用失败,因为StudentID不在SELECT语句中。包括要阅读的列。COLLTB_CollegeID也是如此

因此:

此外,您将结果指定给了错误的属性:

matchingStudent.StudentID = reader.GetInt32(reader.GetOrdinal("StudentID"));
您不能在select语句中以列形式返回StudentID或COLLTB_CollegeID

String sql = "SELECT FirstName, LastName,StudentBiography FROM [PersonTest].[dbo].[StudentAccounts] WHERE StudentID = @p1";
应该是

String sql = "SELECT StudentID, FirstName, LastName, StudentBiography, COLLTB_CollegeID FROM [PersonTest].[dbo].[StudentAccounts] WHERE StudentID = @p1";

尽管您似乎设置了两次matchingStudent.CollegeID,但无论如何,您的返回列中似乎并不需要StudentID

StudentID不是您查询的一部分…就这么简单!你不会在你的选择声明中以列的形式返回StudentID。非常感谢,我犯了一个愚蠢的错误。不客气@camac044-祝你的项目剩余部分好运。请记住标出对您帮助最大的答案,以便社区知道您的问题已经解决。非常感谢!
String sql = "SELECT StudentID, FirstName, LastName, StudentBiography, COLLTB_CollegeID FROM [PersonTest].[dbo].[StudentAccounts] WHERE StudentID = @p1";