简体   繁体   English

在 Dapper.NET 中调整 CommandTimeout?

[英]Adjusting CommandTimeout in Dapper.NET?

I'm trying to run SQL backups through a stored procedure through Dapper (the rest of my app uses Dapper so I'd prefer to keep this portion running through it as well).我正在尝试通过 Dapper 通过存储过程运行 SQL 备份(我的应用程序的其余部分使用 Dapper,所以我更愿意让这部分也通过它运行)。 It works just fine until the CommandTimeout kicks in.它工作得很好,直到 CommandTimeout 开始。

using (var c = SqlConnection(connstring))
{
    c.Open();
    var p = new DynamicParameters();
    // fill out p

    c.Execute("xp_backup_database", p, commandType: CommandType.StoredProcedure);
}

The only CommandTimeout setting I know of is in SqlCommand.我所知道的唯一 CommandTimeout 设置是在 SqlCommand 中。 Is there a way to set this via Dapper?有没有办法通过 Dapper 设置它?

Yes, there are multiple versions of the Execute function.是的,有多个版本的 Execute 函数。 One (or more) of them contains the commandTimeout parameters:其中一个(或多个)包含 commandTimeout 参数:

public static int Execute(this IDbConnection cnn, string sql, 
                dynamic param = null, IDbTransaction transaction = null, 
                            int? commandTimeout = null, CommandType? commandType = null)

Taken from SqlMapper.cs取自SqlMapper.cs

Example from original question with accepted answer added, in case anyone wants it.来自原始问题的示例并添加了已接受的答案,以防万一有人想要。 (Timeout is set to 60 seconds): (超时设置为 60 秒):

using (var c = SqlConnection(connstring))
{
    c.Open();
    var p = new DynamicParameters();
    // fill out p

    c.Execute("xp_backup_database", p, commandTimeout: 60, 
                                       commandType: CommandType.StoredProcedure);
}

There is no need to set command timeout for all queries/Db Calls.无需为所有查询/数据库调用设置命令超时。 You can set globally like below.您可以像下面这样全局设置。

Dapper.SqlMapper.Settings.CommandTimeout = 0;

You can initialize this static property on the application load or in the database class constructor.您可以在应用程序加载时或在数据库类构造函数中初始化此静态属性。

This helps in removing duplication, and in case you decide to change it later, you change it once.这有助于消除重复,如果您决定稍后更改,只需更改一次。

I was able to solve my problem using connection.Query setting the timeout directly我能够使用 connection.Query 直接设置超时来解决我的问题

int timeOutInSeconds = 60;
.
.
.
result = conn.Query<list>(stringQuery, new {parameters, ..}, null, true, timeOutInSeconds).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM