How does Dapper execute query without explicitly opening connection?

喜你入骨 提交于 2019-12-13 18:27:06

问题


We are using Dapper for some data access activity and are using the standard recommended approach for connecting to database as follows:

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

However, if we try and execute a statement, in the docs it show that you need to first state:

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

That means, you have to explicitly open the connection. However, if we leave out the statement conn.open(), it also works and we are worried if in such cases the connection may not be disposed of properly.

I would appreciate any comments as to how the SQL gets executed without explicitly opening any connection.


回答1:


Dapper provide two ways to handle connection.

First is - Allow Dapper to handle it.
Here, you do not need to open the connection before sending it to Dapper. If input connection is not in Open state, Dapper will open it - Dapper will do the actions - Dapper will close the connection.

This will just close the connection. Open/Close is different than Dispose. So, if you really want to Dispose the connection better switch to second way.

Second is - Handle all yourself.
Here, you should explicitly create, open, close and dispose the connection yourself.

Please refer to following links for more details:
https://stackoverflow.com/a/51138718/5779732
https://stackoverflow.com/a/41054369/5779732
https://stackoverflow.com/a/40827671/5779732



来源:https://stackoverflow.com/questions/54388895/how-does-dapper-execute-query-without-explicitly-opening-connection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!