Adjusting CommandTimeout in Dapper.NET?

C#.NetTimeoutDapper

C# Problem Overview


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). It works just fine until the CommandTimeout kicks in.

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. Is there a way to set this via Dapper?

C# Solutions


Solution 1 - C#

Yes, there are multiple versions of the Execute function. One (or more) of them contains the commandTimeout parameters:

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

Solution 2 - C#

Example from original question with accepted answer added, in case anyone wants it. (Timeout is set to 60 seconds):

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

Solution 3 - C#

There is no need to set command timeout for all queries/Db Calls. You can set it 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 in one place.

Solution 4 - C#

I was able to solve my problem using connection.Query setting the timeout directly

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsh-betaView Question on Stackoverflow
Solution 1 - C#jzacharukView Answer on Stackoverflow
Solution 2 - C#Adrian CarrView Answer on Stackoverflow
Solution 3 - C#Mozart AlKhateebView Answer on Stackoverflow
Solution 4 - C#Amanda MataView Answer on Stackoverflow