A while back I wrote an ORM layer for my .net app where all database rows are represented by a subclass of DatabaseRecord
. There are a number of methods like Load()
, Save()
etc. In my initial implementation I created a connection to the DB in the constructor of DatabaseRecord
e.g.
connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString
);
I then call Open()
and Close()
on that SqlConnection at the beginning and end of my methods which access the database. This seemed to me (as someone who was familiar with programming but new to c# and .net) to be the most efficient way to do things - have one connection and open/ close it where necessary within the class.
I've just been doing some reading though and it appears that this pattern is recommended in a number of places:
using (var connection = new SqlConnection(...)) {
connection.Open();
// Stuff with the connection
connection.Close();
}
I can see why it's desirable - the connection is automatically Dispose()
d even if the stuff you do in the middle causes an uncaught exception. I was just wondering what the overhead is for calling new SqlConnection()
potentially many times like this.
Connection Pooling is on so I imagine the overhead is minimal and the second approach should be best practice but I just wanted to make sure my assumptions are right.