How to set command timeout in aspnetcore/entityframeworkcore

In EF Core 3 and above, you can now configure this via connection string. But you need to migrate from 'System.Data.SqlClient' to 'Microsoft.Data.SqlClient'.

Replace System.Data.SqlClient with Microsoft.Data.SqlClient version 2.1.0 or greater.

Then in your connection string simply append the command timeout like so:

"Data Source=SqlExpress;Initial Catalog=YourDatabase;Integrated Security=true;Command Timeout=300"

This will only work with Microsoft.Data.SqlClient 2.1.0 or above, you will get exception if you try this with System.Data.SqlClient.


you can change it through your context

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext()
    {
        Database.SetCommandTimeout(150000);
    }
}

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.


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))
);