使用 Enterprise Library 5.0 数据访问问题
这可能是一个非常简单的问题,但或多或少,我是在问这个问题,这样我就可以了解数据访问块如何打开和关闭连接。
首先,我使用像Enterprise Library这样的东西大约有10年了,并且在Entities等之间来回切换。
无论如何,当我使用Database类的CreateDatabase()函数时,这是否会立即打开到数据库的连接或者当我实际使用 ExecuteReader 之类的东西进行调用时它会打开连接吗?
它如何处理关闭连接?在 DAL 中使用连接后是否必须明确调用关闭连接? Enterprise Library 如何确保在我使用完 Reader 等后关闭连接?
另外,如果 CreateDatabase 立即打开连接,打开和关闭连接的最佳实践是什么?有一小段代码示例可以分享吗?
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 actually 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CreateDatabase() 不会打开与数据库的连接。各个命令通常处理连接的打开和关闭(例如,ExecuteNonQuery)。
当然总有例外。对于 ExecuteReader,立即关闭连接是没有意义的。 ExecuteReader 设置为在释放 DbDataReader 时关闭连接,这就是使用 ExecuteReader 看到此模式的原因:
退出 using 块时,释放 DbDataReader 并关闭连接。
企业库开发人员指南也触及了这个主题。
因此,简而言之,您通常不必处理连接管理。该库将这些工作抽象出来并为您管理。
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:
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.