Using Enterprise Library 5.0 Data Access questions
This might be a very simple question, but more or less, I'm asking to so I can wrap my head around how Data Access blocks opens and closes connections.
First, I have used something like the Enterprise Library for about 10 years, and have switched back and forth between Entities, etc.
Anyway, when I use the CreateDatabase() function of the Database class, does this open a connection immediately to the database OR does it open a connection when I actuall开发者_开发百科y make a call using something like ExecuteReader?
How does it handle closing the connection? Do I explicitly have to call the closing of the connection after using it in a DAL? How does Enterprise Library insure the connection is closed after I'm done with the Reader, etc?
Also, what is the best practices for opening and closing the connection IF CreateDatabase opens the connection immediately? Have a small sample of code to share?
CreateDatabase() does not open a connection to the database. The individual commands typically handle the opening and closing of the connection (e.g. ExecuteNonQuery).
Of course there's always an exception. For ExecuteReader, it wouldn't make sense to close the connection immediately. ExecuteReader is set up to close the connection when the DbDataReader is disposed of, which is why you see this pattern using ExecuteReader:
using (IDataReader reader = db.ExecuteReader(cmd))
{
// Process results
}
when the using block is exited, the DbDataReader is disposed of and the connection is closed.
The Enterprise Library Developer's Guide touches on the subject a bit as well.
So, in short, you typically don't have to deal with connection management. The library abstracts that bit of work away and manages it for you.
精彩评论