索引超出SqlDataReader中的范围异常

时间:2016-01-08 15:02:59

标签: sql-server stored-procedures ado.net indexoutofrangeexception

每当我尝试在ASP.NET MVC项目中使用“在浏览器中查看”选项时,我都会在SqlDataReader中收到错误“index out of range”。

以下是我SqlDataReader的代码:

public List<User> View(ActivityMode a)
{
        SqlConnection con = ConnectionDAL.SQL();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "Sp_UserReg";
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@Activity", a.ToString());

        List<User> lst = null;

        con.Open();

        using (con)
        {
            SqlDataReader DR =cmd.ExecuteReader();

            if (DR.HasRows)
            {
                lst = new List<User>();

                while (DR.Read())
                {
                    User obj = new User();
                    obj.Id = Convert.ToInt32(DR["@Id"]);
                    obj.DOB = Convert.ToDateTime(DR["@DOB"]);
                    obj.EmailAddress = DR["@EmailAddress"].ToString();
                    obj.FirstName = DR["@FirstName"].ToString();
                    obj.LastName = DR["@LastName"].ToString();
                    obj.Password = DR["@Password"].ToString();
                    obj.SecurityAnswer = DR["SecurityAnswer"].ToString();
                    obj.SecurityQuestion = DR["@SecurityAnswer"].ToString();

                    lst.Add(obj);
                }

                lst.TrimExcess();
            }

            return lst;
        }
    }       
}        

代码进入while语句,当它到达Id列时,它会抛出错误。我也试图评论Id,但它在下一栏上给我错误。

以下是数据库中的查询:

ALTER Procedure [dbo].[Sp_UserReg]
    (@Id int = null,
     @FullName varchar(100) = null,
     @Password varchar(50) = null,
     @EmailAddress varchar(50) = null,
     @DOB datetime = null,
     @SecurityQuestion varchar(100) = null,
     @SecurityAnswer varchar(100) = null,
     @Activity varchar(50) = null)
AS BEGIN
    IF(@Activity = 'Add')
        INSERT INTO UserReg (FullName,[Password], EmailAddress, SecurityQuestion, SecurityAnswer, DOB)
        VALUES (@FullName, @Password, @EmailAddress, @SecurityQuestion, @SecurityAnswer, @DOB)

    IF(@Activity = 'Delete')
        DELETE FROM UserReg 
        WHERE id = @id

    IF(@Activity = 'View')
        SELECT * 
        FROM [UserReg]

    IF(@Activity = 'Update')
        UPDATE UserReg 
        SET FullName = @fullName,
            [Password] = @Password,
            EmailAddress = @EmailAddress

    IF(@Activity = 'ViewById')
        SELECT * 
        FROM UserReg 
        WHERE Id = @Id
End

1 个答案:

答案 0 :(得分:0)

在使用数据阅读器引用字段时,您应该删除@符号。