为什么Dapper不需要打开连接?

时间:2022-09-25 12:32:10

The Dapper documentation states that it requires an open connection. However in Steve Michelotti's pluralsight course he doesn't open the connection before executing SQL, and I have found that my own testing connecting to SQL Server and MS Access confirms this.

Dapper文档声明它需要打开连接。然而,在Steve Michelotti的复数课程中,他没有在执行SQL之前打开连接,我发现我自己的连接到SQL Server和MS Access的测试证实了这一点。

Is it best practice to manually control the connections or is it fine to just leave this to Dapper? Are there situations where Dapper absolutely requires that an opened connection is provided?

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

Here is an example of the code that I'm executing against an Access database. At no point do I open the connection, however Dapper happily returns a collection of Fund objects:

这是我正在对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

1 个解决方案

#1


0  

Decided to post this as an answer instead because comments have limited formatting options and max length ... I second TimSchmelter's suggestion, "don't create the connection as field but as local variable." Regardless of whether or not dapper disposes the connection, your code should dispose of it as soon as it is not needed.

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

In this case,

在这种情况下,

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

#1


0  

Decided to post this as an answer instead because comments have limited formatting options and max length ... I second TimSchmelter's suggestion, "don't create the connection as field but as local variable." Regardless of whether or not dapper disposes the connection, your code should dispose of it as soon as it is not needed.

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

In this case,

在这种情况下,

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