Why can Dapper run a query without open a connection?



We use Dapper for various data access tasks and use the generally accepted suggested procedure for establishing a database connection as follows:

public static Func<DbConnection> ConnectionFactory = () => new SqlConnection(ConnectionString);

However, if we attempt to execute a statement, the documentation indicates that you must first state:

using (var conn = ConnectionFactory())
   var result =  await conn.ExecuteAsync(sql, p, commandType: CommandType.StoredProcedure);
   return result;

That implies that you must explicitly establish the connection. However, if we disregard the claimconn.open() , it also functions, and we are concerned that the link would not be appropriately disposed of in such circumstances.

Any feedback on how the SQL is processed, specifically about explicitly initiating any connections, would be really appreciated.

2/4/2019 1:24:02 PM

Accepted Answer

Dapper offers two methods for managing connections.

Allow Dapper to handle it first.
In this case, you may transmit the connection straight to Dapper without first opening it. If the input connection is not in the Open state, Dapper will conduct the operations, open the connection, and then shut it.

As a result, the connection will be cut off. Dispose is different more than Open/Close. So it is best to move to the other method if you truly want to dispose of the connection.

The second is - Take care of everything.
You must specifically construct, open, shut, and dispose of the connection in this case.

For further information, kindly visit the following links:

1/29/2019 7:01:27 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow