A back, I wrote an ORM layer for my .net application, where all database rows are represented by a subclass DatabaseRecord. There are several methods, such as Load(), Save()etc. In my initial implementation, I created a database connection in the constructor DatabaseRecordfor example.
connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString
);
Then I call Open()and Close()this SqlConnection at the beginning and end of my methods that access the database. It seemed to me (as someone who was familiar with programming, but new to C # and .net), to be the most effective way to do something - to have one connection and open / close it where necessary inside the class.
I just read a little and it seems that this pattern is recommended in several places:
using (var connection = new SqlConnection(...)) {
connection.Open();
connection.Close();
}
, - Dispose() d, , , . , new SqlConnection() , .
, , , , , .