How to set CommandTimeout for DbContext?

2019-01-16 22:40发布

I am looking a way to set CommandTimeout for DbContext. After searching I found the way by casting DbContext into ObjectContext and setting value for CommandTimeout property of objectContext.

var objectContext = (this.DbContext as IObjectContextAdapter).ObjectContext;

But I have to work with DbContext.

8条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-16 23:34
var ctx = new DbContext();
ctx.Database.CommandTimeout = 120;
查看更多
男人必须洒脱
3楼-- · 2019-01-16 23:34

I came here looking for an example of setting the timeout for a single command rather than such a global setting.

I figure that it will probably help someone to have an example of how I achieved this:

var sqlCmd = new SqlCommand(sql, context.Database.Connection as SqlConnection);
sqlCmd.Parameters.Add(idParam);
sqlCmd.CommandTimeout = 90;

if (sqlCmd.Connection.State == System.Data.ConnectionState.Closed)
{
    sqlCmd.Connection.Open();
}
sqlCmd.ExecuteNonQuery();
sqlCmd.Connection.Close();
查看更多
登录 后发表回答