如何在 aspnetcore/entityframeworkcore 中设置命令超时

设置命令超时的位置不再与早期版本相同。

然而,我找不到任何地方说明如何改变这一点。

我正在做的是上传非常大的文件,需要比默认的30秒保存。

请注意,我询问的是命令超时,而不是另一个问题中的迁移超时。

85162 次浏览

you can change it through your context

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

The better option is to use CommandTimeout during your context setup like:

public class DbConnect: IConnnectDb
{
private dbentitient _context;


// inject this to a db entity from constructor.


//inside each method now use the follow before u actually run the query to db.


_context.Database.SetCommandTimeout(400);
}

Note: EF Core will only execute the query with less than 100 seconds time. If it's more than that it keeps retrying and you never get to see the result.

That's my experience as of now, so let me know if you are able to fix it EF Core 1.0 does timeout even more fast than EF Core 2.0.

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

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.

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.