How to set command timeout for individual queries in EF Core?

Viewed 1815

I know the command timeout can be set using the context.Database.SetCommandTimeout method. But this changes the timeout for all the queries that are made using the same DbContext instance.

I know I can set the timeout, run the query and reset the timeout, but this feels like a hack. I want to set the timeout per query. Similar to how SqlCommand.CommandTimeout can be set in ADO.NET for each query. Is it possible to do that with EF Core?

1 Answers

As I've said in my comment, it isn't something I think is necessary or really really useful. I've debugged a little the code of EF Core (it is quite easy with VS 2019, by letting it load the symbols from the nuget server or by forcing it to decompile to source code). There are some "insertion points" we could call where you could inject something to modify the SetCommandTimeout for a single query. For example for LINQ queries a

public class MyCommandInterceptor : DbCommandInterceptor
{
    public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
    {
        return base.ReaderExecuting(command, eventData, result);
    }
}

with an

.AddInterceptors(new MyCommandInterceptor()); 

put where you configure your DBContext is probably the best place. When the interceptor is run the DbCommand command has already the standard Timeout set and you can change it. The problem cleary is setting the timeout you want and passing this information to the interceptor. This is complex and I'm not sure that there are good solutions (I think there are various ugly solutions... It seems to be difficult to add informations during query building and letting the interceptor know about this information)

If you are interested, the DbCommand is created in Microsoft.EntityFrameworkCore.Storage.CreateDbCommand().

If you want something pre-packaged the response is no, there is nothing. You are clearly free to suggest it as feature in the efcore github. If modifying the source code of EF it would be relatively easy to add this feature.

Related