gpt4 book ai didi

.net - 为什么 Dapper 不需要开放连接?

转载 作者:行者123 更新时间:2023-12-02 14:14:43 29 4
gpt4 key购买 nike

Dapper 文档指出它需要 open connection 。然而在 Steve Michelotti 的 pluralsight course 中他在执行 SQL 之前不会打开连接,我发现我自己对 SQL Server 和 MS Access 连接的测试证实了这一点。

手动控制连接是最佳实践还是将其留给 Dapper 即可?是否存在 Dapper 绝对要求提供打开的连接的情况?

下面是我针对 Access 数据库执行的代码示例。我永远不会打开连接,但是 Dapper 很乐意返回 Fund 对象的集合:

Private ReadOnly _conn As IDbConnection = New OleDbConnection(ConnectionStrings.GetAccessConnectionString(ConnectionStrings.AccessVersion.v2003,
ConfigurationManager.AppSettings("MSAccessLocation"), ""))
Public Function GetAll() As List(Of Fund) Implements IFundRepository.GetAll
Return _conn.Query(Of Fund)("SELECT * FROM Funds").ToList()
End Function

最佳答案

决定将其作为答案发布,因为注释的格式选项和最大长度有限......我赞同 TimSchmelter 的建议,“不要将连接创建为字段,而是创建为局部变量。”无论 dapper 是否处置连接,您的代码都应该在不需要时立即处置它。

在这种情况下,

Public Function GetAll() As List(Of Fund) Implements IFundRepository.GetAll

Using conn As IDbConnection = New DbConnection (_connectionString)

Dim funds As List(Of Fund) = _conn.Query(Of Fund)("SELECT * FROM Funds").ToList()

Return funds

End Using

End Function

关于.net - 为什么 Dapper 不需要开放连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30737010/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com