Wednesday, March 7, 2012

Closing a SqlDataReader after calling from a DAL....?

I have a DAL that I'm trying to implement - the issue is that I want to call a reader from the DAL, but I'm not sure how to close it. I got best practices from MSDN (located here:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatasqlclientsqldatareaderclasstopic.asp ) regarding the SqlDataReader, but can't seem to figure out how to close when using DAL.

Here is sample code in C#:

NOTE: Everything WORKS just fine, however in the DAL for GetRoutes, I can't seem to figure out how to close the reader (see comments in function):

mydatapage.aspx
.
.
.
//Populating some Drop Down List:
private void ddlRoutes_SelectedIndexChanged(object sender, System.EventArgs e) {
SqlDataReader dr = DAL.GetRoutes(ddlRoutes.SelectedValue.ToString());
while (dr.Read())
{
.
.
.
}
}

DataAccessLayer.cs
.
.
.
public static SqlDataReader GetRoutes(string sIdx){
cnn = new SqlConnection(ConnectionString);
cnn.Open();
SqlCommand cmd = new SqlCommand();
SqlParameter par = new SqlParameter();
cmd.Connection=cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_GetRoutes";

return cmd.ExecuteReader();

//Everything works above, however I would think that something
//like this SHOULD work, but doesn't:
//
// SqlDataReader dr;
// dr = cmd.ExecuteReader()
// return dr;
// cnn.close();
}


Right now, you pass the SqlDataReader to the method in your page. If you reverse this--andpass the method to the SqlDataReader--your DAL can maintain control of the reader and the database connection.

To learn how to do this, please read the following article:Using Delegates with Data Readers to Control DAL Responsibility

|||

what you have to do is follwing

dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

then when you close dr it will close the connection. However passing datareader around is not a good idea. It should stay in your DAL.

No comments:

Post a Comment