最近、コードがすべてこの一般的な形式をとるデータアクセス層の選択メソッドを書いていることに気づきました。
public static DataTable GetSomeData( ... arguments)
{
string sql = " ... sql string here: often it's just a stored procedure name ... ";
DataTable result = new DataTable();
// GetOpenConnection() is a private method in the class:
// it manages the connection string and returns an open and ready connection
using (SqlConnection cn = GetOpenConnection())
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
// could be any number of parameters, each with a different type
cmd.Parameters.Add("@Param1", SqlDbType.VarChar, 50).Value = param1; //argument passed to function
using (SqlDataReader rdr = cmd.ExecuteReader())
{
result.Load(rdr);
}
}
return result;
}
またはこのように:
public static DataRow GetSomeSingleRecord( ... arguments)
{
string sql = " ... sql string here: often it's just a stored procedure name ... ";
DataTable dt = new DataTable();
// GetOpenConnection() is a private method in the class:
// it manages the connection string and returns an open and ready connection
using (SqlConnection cn = GetOpenConnection())
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
// could be any number of parameters, each with a different type
cmd.Parameters.Add("@Param1", SqlDbType.VarChar, 50).Value = param1; //argument passed to function
using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
dt.Load(rdr);
}
}
if (dt.Rows.Count > 0)
return dt.Rows[0];
return null;
}
これらのメソッドは、ベースの DataTable または DataRecord を、プレゼンテーション層が使用できる厳密に型指定されたビジネス オブジェクトに変換するビジネス層コードによって呼び出されます。
同様のコードを繰り返し使用しているので、このコードが最善であることを確認したいと思います。では、どうすれば改善できるでしょうか?そして、共通コードをこれから独自のメソッドに移動しようとする価値はありますか。もしそうなら、そのメソッドはどのように見えますか (特に SqlParameter コレクションを渡すことに関して)?