Add new constructor to Database classes

Topics: Building and extending application blocks, Data Access Application Block
Dec 15, 2010 at 12:35 AM
Edited Dec 15, 2010 at 12:49 AM

I'm using NHibernate in a project, but for stored procedure calls, I'd like to use the open connection from the open session with the Enterprise Library. Is there any way we could add a constructor that takes a connection instead of a connection string? I imagine others would find it useful also.

If there is already a way to do this, can someone give me some guidance?

Dec 15, 2010 at 6:03 AM

Unfortunately DAAB doesn't have this constructor and I don't know if there is any extension that has already been built to support this. DAAB is built on top of ADO.NET so what I think you can do is you can supply your connection object into your DbCommand object Connection property. Which may look something like this;

            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("SQLConn");

            DbCommand cmd = db.GetSqlStringCommand("Select * FROM Products");      
            DbConnection conn = new SqlConnection("Data Source=.; Initial Catalog=Products;Integrated Security=false") as DbConnection;
            cmd.Connection = conn;

            conn.Open();
            SqlDataAdapter dadapter = new SqlDataAdapter();
            dadapter.SelectCommand = (SqlCommand) cmd;
            DataSet dset = new DataSet();
            dadapter.Fill(dset);
            conn.Close();

But since that we have already bypass DAAB in this approach then what are we doing in this is more of a standard ADO. Which also means you will be the one responsible managing the connections. Hope this helps.

Gino Terrado
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Dec 15, 2010 at 10:32 PM
Edited Feb 24, 2011 at 3:05 AM

[Updated]

I'm not sure if you're ok with this approach but if you open a connection and transaction prior to executing a command, EntLib will use that open connection to execute it.

dbConnection.Open();
using(dbConnection)
{
        using(DbTransaction trans = dbConnection.BeginTransaction())
        {
                db.ExecuteNonQuery(command, trans);
                trans.Commit();
        }
}
 

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com