Your issue with EF 6 query timeouts, despite efficient SQL in SSMS, suggests parameter sniffing. To resolve this, consider the following:
Can EF Embed "OPTION RECOMPILE" Hint?
Yes, EF 6 allows for interception of SQL commands before execution. You can add the "OPTION RECOMPILE" hint by implementing an IDbCommandInterceptor. Here's an example implementation:
public class OptionRecompileHintDbCommandInterceptor : IDbCommandInterceptor { public void AddQueryHint(IDbCommand command) { if (command.CommandType != CommandType.Text || !(command is SqlCommand)) return; if (command.CommandText.StartsWith("select", StringComparison.OrdinalIgnoreCase) && !command.CommandText.Contains("option(recompile)")) { command.CommandText = command.CommandText + " option(recompile)"; } } // Implementation of other interface methods... }
To use this interceptor, simply add it to your application at the start:
DbInterception.Add(new OptionRecompileHintDbCommandInterceptor());
Further Considerations
The above is the detailed content of How Can I Resolve EF 6 Query Timeouts Caused by Parameter Sniffing?. For more information, please follow other related articles on the PHP Chinese website!