0

I know I need to use the using statement to use a database connection, to be sure that it will be automatically closed without further worries.

But I am using a masterpage and a content page which both are needing to retrieve data from a the dataabse, and both have their own using statement. So for every request, I am still using two database connections.. How can that be prevented? I would like to be using one database connection only for each request.

And there is a special case: I also use caching, so in some cases there is no need to have a database connection at all, since the data is retrieved from the cache. So then I would want that no database connection is created at all...

I could not find any practical solution or example about this.. can anybody give me a hint?

Allie
  • 1,081
  • 1
  • 13
  • 17

2 Answers2

1

If you use the MasterType directive in the content page, it can access public variables, including a connection object, in the MasterPage.

http://msdn.microsoft.com/en-us/library/ms228274%28v=vs.80%29.aspx/css

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • ok, this actually works when I do the following: create a public connection variable on the masterpage, initialize and reuse that variable anywhere I am using that connection, and close the connection using the Page_UnLoad of the masterpage. Then I have exactly at most one connection for each request. – Allie May 15 '13 at 15:29
0

This depends on the architecture of your application but assuming the masterpage owns the content page you should simply pass the connection into the content pages methods. For example

 //in master page pseudo code
 public void UpdateRecord(string updateField)
 {
       using (myConnection = new connection())
       {
            //master page does something with db
            try
            {
                  ContentPage.GetContent(myConnection);
            }
            catch
            {
                 // handle expected errors
                 // fail on other ones
            }
       }
 }
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115