Dapper如何在不显式打开连接的情况下执行查询? [英] How does Dapper execute query without explicitly opening connection?

查看:165
本文介绍了Dapper如何在不显式打开连接的情况下执行查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用Dapper进行某些数据访问活动,并使用推荐的标准方法来连接数据库,如下所示:

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;
}

这意味着您必须显式打开连接。但是,如果我们忽略语句 conn.open(),它也可以工作,并且我们担心在这种情况下可能无法正确处理连接。

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.

推荐答案

Dapper提供了两种处理连接的方法。

Dapper provide two ways to handle connection.

第一种是-允许Dapper处理它。

在这里,您无需先打开连接,再将其发送到Dapper。如果输入连接未处于打开状态,则Dapper将打开它-Dapper将执行操作-Dapper将关闭连接。

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.

这只会关闭连接。 打开/关闭不同于Dispose。因此,如果您真的想处置连接,最好改用第二种方法。

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.

请参考以下链接以获取更多详细信息:

https://stackoverflow.com/a/51138718/5779732

https://stackoverflow.com/a/41054369/5779732

https://stackoverflow.com/a/40827671/5779732

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

这篇关于Dapper如何在不显式打开连接的情况下执行查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆