c# - 如何更改超时查询

标签 c# sql entity-framework

对于包含很多记录的查询,我遇到了超时问题。如何更改查询超时?

我试过用这种方式更改超时连接,但它不起作用:

connection.ConnectionTimeout = 60;//不工作(就绪)

类:

public abstract class RepositoryBase<TEntity> : IRepositoryBase<TEntity>, IDisposable where TEntity : class
{
    protected SqlConnection _connection;
    protected string _connectionString;

    public RepositoryBase(string connectionString)
    {
        _connectionString = connectionString;
        SqlConnection connection = new SqlConnection(connectionString);
        if (connection.State == ConnectionState.Closed)
            connection.ConnectionTimeout = 60; // not working (ready)
            connection.Open();

        _connection = connection;
    }

    public List<T> GetEntitiesByQuery<T>(string Query)
    {
        using (var connection = _connection)
        {
            try
            {
                var entities = connection.Query<T>(Query);
                return entities.ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                connection.Close();
            }
        }
    }
}

最佳答案

您需要设置 CommandTimeout 属性:

The time (in seconds) to wait for the command to execute. The default value is 30 seconds.

如何设置取决于所使用的数据访问技术。

对于普通的 ADO.NET:

IDbCommand cmd = ...;
cmd.CommandTimeout = 120; // 2 min

对于 EF6:

DbContext db = ...;
db.Database.CommandTimeout = 120; // 2 min

但看起来你正在使用 Dapper . Query<T>当前使用的方法具有以下签名:

public static IEnumerable<T> Query<T>(
    this IDbConnection cnn,
    string sql,
    object param = null,
    IDbTransaction transaction = null,
    bool buffered = true,
    int? commandTimeout = null,
    CommandType? commandType = null
)

如您所见,有很多可选参数,其中之一是commandTimeout。你需要。所以你可以使用这样的东西:

var entities = connection.Query<T>(Query, commandTimeout: 120);

或者您可以为所有查询设置默认超时:

SqlMapper.Settings.CommandTimeout = 120; // 2 min

关于c# - 如何更改超时查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52095934/

相关文章:

winforms - 如何使用 EF 4.1 Code First 加密连接字符串?

c# - 如何强制 AbstractValidator 中的 IRuleBuilder 充当 'if' 语句?

c# - 如何查找 OpenReadAsync 方法抛出的异常

mysql - 为什么 MYSQL Sleep(x) 会永远持续下去?

c# - SQL Server 2008 选择在

SQL转换加where

c# - 如何在 Entity Framework 6 中包含所有关系?

c# - LINQ:如何在 Any() 方法之后选择一列

c# - 从 PNG 到 BitmapImage。透明度问题。

c# - 如何在 C# 中使用 EWS 托管 API 订购电子邮件