Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set command timeout in aspnetcore/entityframeworkcore

The place where the command timeout is set is no longer the same as earlier versions.

However, I cannot find anywhere that says how to change this.

What I am doing is uploading very large files which takes longer than the default 30 seconds to save.

Note that I ask about Command Timeout, not Migration Timeout as in another question.

like image 230
Greg Gum Avatar asked Aug 20 '16 20:08

Greg Gum


People also ask

How do I set the execution timeout in Entity Framework?

Set database timeout in Entity Framework Try this on your context:...public class MyDatabase : DbContext { public MyDatabase () : base(ContextHelper. CreateConnection("Connection string"), true) { ((IObjectContextAdapter)this). ObjectContext. CommandTimeout = 180; } } ...

How do I set timeout in .NET core?

But according to the documentation you can just add web. config to your project and specify this (and other) setting value: Setting the RequestTimeout="00:20:00" on the aspNetCore tag and deploying the site will cause it not to timeout.

What is command timeout in C#?

The CommandTimeout property sets or returns the number of seconds to wait while attempting to execute a command, before canceling the attempt and generate an error. Default is 30.


3 Answers

If you're using the DI container to manage the DbContext (i.e. you're adding the DbContext to the service collection), the command timeout can be specified in the options.

In Startup.ConfigureServices:

services.AddDbContext<YourDbContext>(options => options.UseSqlServer(
    this.Configuration.GetConnectionString("YourConnectionString"),
    sqlServerOptions => sqlServerOptions.CommandTimeout(60))
);
like image 59
Carl Sharman Avatar answered Oct 23 '22 09:10

Carl Sharman


you can change it through your context

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext()
    {
        Database.SetCommandTimeout(150000);
    }
}
like image 21
The Integrator Avatar answered Oct 23 '22 10:10

The Integrator


If you would like a temporary increase timeout only for one Context instance.

Let's say for 1 request (default Scoped context lifetime)

Change this before long running query:

Context.Database.SetCommandTimeout(TimeSpan.FromMinutes(20))

With scoped lifetime you can specify timeout only once and you do not have to specify it in any subsequent services constructors injections.

like image 35
Oleg Avatar answered Oct 23 '22 11:10

Oleg