Closing adatper connection after manually opening

Posts   
 
    
AlbertK
User
Posts: 44
Joined: 23-Dec-2009
# Posted on: 28-Oct-2010 17:23:38   

I saw some related posts, but I want to double check something.

I have a factory class that returns DataAccessAdapter:


        public static DataAccessAdapter GetDataAdapterForUpdate(string connString)
        {
            DataAccessAdapter a = new DataAccessAdapter(connString);

            a.KeepConnectionOpen = true;

            a.OpenConnection();
            //Do some other stuff here that requires connection to be open
            return a;
        }

Since I manually called OpenConnection, do I need to explicitely call CloseConnection or is it sufficient to wrap adapter with using() scope? Below, is example 1 safe/sufficient or do I need to go with example 2?

Example 1:


using (DataAccessAdapter a = MyDataAdapterFactory.GetDataAdapterForUpdate())
{
    //use adapter here
}

Example 2:


using (DataAccessAdapter a = MyDataAdapterFactory.GetDataAdapterForUpdate())
{
    try { }
    finally { a.CloseConnection(); }
}

Thank you.

MTrinder
User
Posts: 1461
Joined: 08-Oct-2008
# Posted on: 28-Oct-2010 22:05:24   

I've never used .OpenConnection or .CloseConnection in 7 years of using LLBLGen - I'm not sure why you would need to.

Example 1 is the recommended option.

Matt

AlbertK
User
Posts: 44
Joined: 23-Dec-2009
# Posted on: 28-Oct-2010 22:41:18   

Hi Matt, we have database environment where changes have to be audited on the database level using triggers. The trigger needs to log the end-user who initiated insert/update/delete action. Since the code runs under service account (WCF), it needs to propagate end-user information to the database. Triggers expect that the calling code will set end-user info inside a database connection context. So, I have code that always executes


set context_info 'someuser'

whenever I get a new instance of DataAdapter for insert/update/delete. Hence the need for a factory class and the need to open a connection explicitely.

Thanks.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 29-Oct-2010 05:51:52   

AlbertK wrote:

Example 1:


using (DataAccessAdapter a = MyDataAdapterFactory.GetDataAdapterForUpdate())
{
    //use adapter here
}

That will automatically dispose the DataAccessAdapter instance, and will automatically close the active connection. So that is enough wink

David Elizondo | LLBLGen Support Team