Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come posso specificare un suggerimento per l'indice in Entity Framework?

La soluzione è semplice. Aggiungiamo un Interceptor!!!

    public class HintInterceptor : DbCommandInterceptor
{
    private static readonly Regex _tableAliasRegex = new Regex(@"(?<tableAlias>AS \[Extent\d+\](?! WITH \(*HINT*\)))", RegexOptions.Multiline | RegexOptions.IgnoreCase);

    [ThreadStatic] public static string HintValue;

    public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        if (!String.IsNullOrWhiteSpace(HintValue))
        {
            command.CommandText = _tableAliasRegex.Replace(command.CommandText, "${tableAlias} WITH (*HINT*)");
            command.CommandText = command.CommandText.Replace("*HINT*", HintValue);
        }

        HintValue = String.Empty;
    }

    public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        if (!String.IsNullOrWhiteSpace(HintValue))
        {
            command.CommandText = _tableAliasRegex.Replace(command.CommandText, "${tableAlias} WITH (*HINT*)");
            command.CommandText = command.CommandText.Replace("*HINT*", HintValue);
        }

        HintValue = String.Empty;
    }
}

La regex potrebbe essere migliore, lo so. Registriamo il nostro Interceptor nella classe Config

public class PbsContextConfig : DbConfiguration
{
    public PbsContextConfig()
    {
        this.AddInterceptor(new HintInterceptor());
    }
}

Facciamo una bella estensione Hint per DbSet

public static class HintExtension
{
    public static DbSet<T> WithHint<T>(this DbSet<T> set, string hint) where T : class
    {
        HintInterceptor.HintValue = hint;
        return set;
    }
}

Come si usa?

context.Persons.WithHint("INDEX(XI_DOWNTIME_LOCK)").Where( x => x.ID == ....

Le modifiche sono benvenute!