Execute Reader没有返回结果

时间:2018-02-25 02:41:44

标签: sql-server asp.net-core-mvc

你能帮我看看我的代码有什么问题吗?如果我使用Id的a参数运行存储过程,我在SQL Server中得到一个结果。但是,当我使用Id的相同值时,使用下面的代码,在我的if(rdr.HasRows)..中,我得到了错误。

public Student Find(int key)
{
    string connectionPath = ConnectionStrings.DbConnection;
    Student student = null;

    try
    {
        using(var sqlCon = new SqlConnection(connectionPath))
        {
            sqlCon.Open();

            using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon))
            {
                cmd.Parameters.AddWithValue("@Id", key);

                using(var rdr = cmd.ExecuteReader(CommandBehavior.SingleResult))
                {
                    if (rdr.HasRows)
                    {
                        while (rdr.Read())
                        {
                            student = new Student
                            {
                                Age = Convert.ToInt32(rdr["Age"]),
                                FirstName = rdr["FirstName"].ToString(),
                                LastName = rdr["LastName"].ToString(),
                                Gender = rdr["Gender"].ToString()
                            };
                        }
                    }
                }
            }
        }
    }
    catch(Exception ex)
    {
        throw ex;
    }

    return student;
}

如果我尝试获取所有记录,我不会遇到任何问题:

public IEnumerable<Student> GetAll()
{
    var studentList = new List<Student>();

    try
    {
        string connectionPath = ConnectionStrings.DbConnection;

        using(var sqlCon = new SqlConnection(connectionPath))
        {
            using(var cmd = new SqlCommand("Sp_GetStudents", sqlCon) { CommandType = CommandType.StoredProcedure})
            {
                sqlCon.Open();

                using(var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    while (rdr.Read())
                    {
                        studentList.Add
                            (
                                new Student
                                {
                                    Id = Convert.ToInt32(rdr["Id"]),
                                    Age = Convert.ToInt32(rdr["Age"]),
                                    FirstName = rdr["FirstName"].ToString(),
                                    LastName = rdr["LastName"].ToString()
                                }
                            );
                    }
                }
            }
        }
    } 
    catch(Exception ex)
    {
        throw ex;
    }

    return studentList;
}

这是使用asp.net核心

0 个答案:

没有答案