对于包含很多记录的查询,我遇到了超时问题。如何更改查询超时?
我试过用这种方式更改超时连接,但它不起作用:
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/