33

I cannot find the a way to set the command timeout of a linq query using entity framework 4.3 and its' DbContext. How do I increase Commandtimeout in entity framework?

EDIT I am actually looking for Command Timeout increase. I confused the two, it is the sql command that is timing out not the connection.

Thanks

Saher Ahwal
  • 9,015
  • 32
  • 84
  • 152

3 Answers3

64

If you're using DbContext, you'll first need to drop down to ObjectContext:

((IObjectContextAdapter)context).ObjectContext.CommandTimeout = 180;
Saher Ahwal
  • 9,015
  • 32
  • 84
  • 152
bricelam
  • 28,825
  • 9
  • 92
  • 117
11

I added the command timeout value in my Context class in an attempt to handle longer processing times for some of the stored procedures that are populating my application. Seems to have done the trick.

public partial class ExampleEntities : DbContext
    {
        public ExampleEntities()
            : base("name=ExampleEntities")
        {
            ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
Maurice Jordan
  • 111
  • 1
  • 3
  • Perfect answer with sample code where to put. Thanks. – sapatelbaps Apr 07 '16 at 06:25
  • 1
    Note that since this class is usually generated code, it would probably be better to make this change in the .tt file or some other initialization code. Otherwise the change will get clobbered next time you update the data model and regenerate. – Tim Sparkles Mar 19 '20 at 22:51
9

this command is enough.

((System.Data.Entity.Infrastructure.IObjectContextAdapter) context).ObjectContext.CommandTimeout
                = 180;
m-Abrontan
  • 503
  • 4
  • 7