Sqlserver
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Sqlserver

Làm cách nào để chỉ định gợi ý chỉ mục trong Entity Framework?

Giải pháp rất đơn giản. Hãy thêm một 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;
    }
}

Tôi biết regex có thể tốt hơn. Hãy đăng ký Interceptor của chúng tôi trong lớp Cấu hình

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

Hãy tạo phần mở rộng Gợi ý cho 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;
    }
}

Làm thế nào để sử dụng?

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

Các sửa đổi được hoan nghênh!



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cách ánh xạ nhiều phân vùng thành một nhóm tệp trong SQL Server (T-SQL)

  2. TODATETIMEOFFSET () Ví dụ trong SQL Server

  3. DateDiff để xuất giờ và phút

  4. Truy vấn PIVOT trên các bản ghi riêng biệt

  5. Cách mã hóa một dạng xem trong SQL Server