I am experiencing parameter sniffing problem sometimes. So I would like to add OPTION (RECOMPILE) to the end of query to fix it. How can I do it in EF 6?
Another option to install EF is to run the following command in the Package Manager Console: PM> Install-Package EntityFramework Once EF is added to the project and we have our data model, we need to create a Context. Contextdefines a session with the database, allowing us to query and save the data.
It let the developers work with data on a higher level of abstraction without the need to worry about the database type or structure where the data is stored. The focus of this article will be to show and explain how easy it is to add an Entity Framework to a .NET project.
If we know that a statement returns a varying amount of data (based on the parameters supplied) then we can use the SQL Server 2005 feature WITH RECOMPILE to tell SQL Server that the statement being executed should have it’s own plan created and that prior plans (if they exist) should not reuse the statement.
Occasionally, query hints become very important, such as when you need to lock records in a query. Unless we find a way to use hints with Entity Framework, we are forced to use stored procedures with Entity Framework, which will increase the dependency on synchronised changes in the database when refectoring data objects in the application.
I implemented IDbCommandInterceptor interface to fix the parameter sniffing error.
The usage of the new interceptor:
using (var dataContext = new AdventureWorks2012Entities())
{
var optionRecompileInterceptor = new OptionRecompileInterceptor();
DbInterception.Add(optionRecompileInterceptor);
string city = "Seattle";
var seattle = (
from a in dataContext.Addresses
where a.City == city
select a).ToList();
DbInterception.Remove(optionRecompileInterceptor); //Remove interceptor to not affect other queries
}
Implementation of the interceptor:
public class OptionRecompileInterceptor : DbCommandInterceptor
{
static void AddOptionToCommand(DbCommand command)
{
string optionRecompileString = "\r\nOPTION (RECOMPILE)";
if (!command.CommandText.Contains(optionRecompileString)) //Check the option is not added already
{
command.CommandText += optionRecompileString;
}
}
public override void NonQueryExecuting(
DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
AddOptionToCommand(command);
}
public override void ReaderExecuting(
DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
AddOptionToCommand(command);
}
public override void ScalarExecuting(
DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
AddOptionToCommand(command);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With