如何在实体框架中指定索引提示? [英] How can I specify an index hint in Entity Framework?
本文介绍了如何在实体框架中指定索引提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
select * from table1 with(index=IX_table1_1)
Linq to sql 使用ado.net 实体想写上面的代码.找不到实体,特别是索引提示的使用.
Linq to sql using ado.net entity would like to write the above code. I could not find entity in particular, the use of the index hint.
var querysample = from a in db.table1
select a;
推荐答案
解决方案很简单.让我们添加一个拦截器!!!
Solution is simple. Let's add an Interceptor !!!
public class HintInterceptor : DbCommandInterceptor
{
private static readonly Regex _tableAliasRegex = new Regex(@"(?<tableAlias>AS [Extentd+](?! 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;
}
}
正则表达式可能会更好,我知道.让我们在 Config 类中注册我们的拦截器
The regex could be better, i know. Let's register our Interceptor in Config class
public class PbsContextConfig : DbConfiguration
{
public PbsContextConfig()
{
this.AddInterceptor(new HintInterceptor());
}
}
让我们为 DbSet 制作漂亮的提示扩展
Let's make nice Hint Extension for 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;
}
}
如何使用?
context.Persons.WithHint("INDEX(XI_DOWNTIME_LOCK)").Where( x => x.ID == ....
欢迎修改!
这篇关于如何在实体框架中指定索引提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文