I am trying to improve my web app code bu moving functions to a separate Class file which in contained in the App_Code folder.
My first attempt which calls a method from my web form codebehind (including a string value), the method then calls a SQL Stored Procedure which uses the string value as an SP Parameter, the resulting DataReader (which may contain multiple data rows) is returned to the web form.
Whilst this does work, I am concerned about the database connection. If I close it in the Method, then I get an error (as expected). I cannot seem to close the connection in the web form as it does not exist. What should I do? Maybe I should return something other than a DataReader?
WebForm Code Behind
SqlDataReader myReader = new CSEmployee().EmployeeGetDetails(pmfkey.Text);
if (myReader.HasRows)
{
while (myReader.Read())
{
// do something
}
}
Class Code Page
public SqlDataReader EmployeeGetDetails(string pmfkey)
{
SqlCommand cmd = new SqlCommand("sp_Employee_GET_Details", dbEmpConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@pmfkey", SqlDbType.NVarChar).Value = pmfkey;
SqlDataReader oDataReader = null;
dbEmpConn.Open();
oDataReader = cmd.ExecuteReader();
//dbEmpConn.Close(); - This causes error (as expected)
return oDataReader;
}