Why doesn't Dapper require an open connection?

Dapper documentation says that this requires opening a connection . However, in Steve Michelotti's reusable course, it doesn't open a connection before executing SQL and I found my own testing connecting to SQL Server and MS Access confirms this.

Is it better for you to manually manage connections, or is that fine, just leave it to Dapper? Are there situations where Dapper absolutely requires an open connection?

Here is some sample code I am running against an Access database. Under no circumstances do I open the connection, however Dapper happily returns a collection of Fund objects:

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

      

+3


source to share


1 answer


Decided to post this as an answer instead, because comments have limited formatting options and maximum length ... I am second, TimSchmelter's suggestion: "Don't create the connection as a field but as a local variable." Regardless of whether dapper uses a connection, your code should dispose of it as soon as it doesn't need it.

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

      

0


source







All Articles