1

ASP.NET Web サイト内の顧客 ID などにアクセスできるように、データベースからデータ オブジェクトを返そうとしています。顧客がログインすると、オブジェクトが返されます。ただし、次のエラーが表示されます。

   'Invalid attempt to read when no data is present.' 

正しい情報を返すデータベース(ストアドプロシージャの実行)でSQLクエリを完了したので、そこにあることがわかりました。次の方法に何か問題があるとしか推測できません。

    using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
        {
            using (SqlCommand sqlComm = new SqlCommand("Select_Customer_By_UserName_And_Password", sqlConn))
            {
                sqlComm.Connection.Open();
                try
                {
                    sqlComm.CommandType = CommandType.StoredProcedure;
                    sqlComm.Parameters.Add("@Username", SqlDbType.NVarChar, 25).Value = pUsername;
                    sqlComm.Parameters.Add("@Password", SqlDbType.NVarChar, 25).Value = pPassword;

                    using (SqlDataReader sqlDR = sqlComm.ExecuteReader(CommandBehavior.SingleRow))
                    {
                        if (sqlDR.HasRows)
                        {
                            //Creating the new object to be returned by using the data from the database.
                            return new Customer
                            {
                                CustomerID = Convert.ToInt32(sqlDR["CustomerID"])
                            };
                        }
                        else
                            return null;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    sqlComm.Connection.Close();
                }
            }
        }
4

1 に答える 1

3

を呼び出す必要がありますsqlDR.Read()。そうしないと、「レコード ポインタ」がレコードを指します。HasRows実際に読み取ることができる行があることを示すだけです。各行 (または最初の行のみ) を読み取るには、1Read回またはwhileループで呼び出す必要があります。

例えば:

if (reader.HasRows)
{
    while (reader.Read())
        ...
}

コードは次のようになります。

using (SqlDataReader sqlDR = sqlComm.ExecuteReader(CommandBehavior.SingleRow))
{
    if (sqlDR.Read())
    {
        //Creating the new object to be returned by using the data from the database.
        return new Customer
        {
            CustomerID = Convert.ToInt32(sqlDR["CustomerID"])
        };
    }
    else
        return null;
}

ところで、usingパラメーター化されたクエリの使用、おめでとうございます!

于 2013-02-06T12:33:36.363 に答える