1

I want all normal commands to have default timeout of 30 sec, but for one stored proc I need 5 min.

I don't want do this this unless it's the only way.

public partial class AContext : DbContext
{
    public AContext(string connectionString)
        : base(connectionString)
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;
    }
}

How to attach timeout to this query only?

Context.Database.SqlQuery<AAAAA>("usp_AAAAA");
1
  • change it before executing the stored procedure and revert it after done :) Commented Aug 9, 2016 at 21:06

1 Answer 1

3

You can set the CommandTimeout on the Database property of the DbContext directly, no need to try to get the object context from the DbContext.

Create a new DbContext instance just for your execution and then get rid of it.

If you have a shared DbContext instance you will have to wrap the call in a try/finally block and reset the timeout in the finally, this is so that the timeout will be reset even in the event of failure.

using(var Context = new AContext())
{
    Context.Database.CommandTimeout = 60*5; // 5 minutes
    var result = Context.Database.SqlQuery<AAAAA>("usp_AAAAA");
}

If the Context is shared.

try
{
    Context.Database.CommandTimeout = 60*5; // 5 minutes
    var result = Context.Database.SqlQuery<AAAAA>("usp_AAAAA");
}
finally{
    Context.Database.CommandTimeout = null; // reset
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.