0

次のクエリがあります。

public static string GetCustomerName(string customerNo)
{
   string query = "query to get customer";
   var myConn= new MYConnection();
   using (SqlConnection con = new SqlConnection(myConn.MYConnectionString))
   {
       con.Open();
       SqlCommand cmd = new SqlCommand(query, con);
       cmd.Parameters.Add("@customerNo", SqlDbType.NVarChar).Value = customerNo;
       object result = cmd.ExecuteScalar();
       return result == DBNull.Value ? String.Empty : (string)result;
   }

}

上記のメソッドを次のように呼び出しています。

string customerName = GetCustomerName(CustomerID);

if (customerName.Contains(Constants.Company.CompanyName))
{

    Additional Logic...
}

ただし、メソッドが顧客名を返さない場合、Object Reference Null エラーが発生します。GetCustomer メソッドは空の文字列を返すと思います。

CustomerName を取得する呼び出しを以下に変更すると、完全に機能します。

string customerName = GetCustomerName(emailAndSTCodeInfo.CustomerID);
if (String.IsNullOrEmpty(customerName))
{
    customerName = "";
}
if (customerName.Contains(Constants.Chase.ACCOUNT_NAME))
{
    Additional Logic
}

したがって、私の質問は、GetCustomer メソッドがレコードを見つけられず、null を返す場合、これを処理する適切な方法は何であるかということです。現在、上記の作業コードを使用していますが、ハックか何かのようです。

どんな助けでも大歓迎です。

4

2 に答える 2

2

クエリが行を返さない場合、 で実行するとではなくExecuteScalarが返されます。nullDBNull.Value

したがって、メソッドは戻り値とGetCustomerNameをチェックする必要があります。nullDBNull.Value

于 2013-04-30T18:01:25.567 に答える
2

ExecuteScalarレコードが返されない場合は null を返します。

が null を返さないことを保証するにGetCustomerNameは、最後の行を次のように変更できます。

return Convert.ToString(result);

Convert.ToString(object)引数が null または の場合、空の文字列を返しますDBNull.Value

于 2013-04-30T18:01:41.590 に答える