向表添加索引 [英] Adding index to a table

查看:105
本文介绍了向表添加索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表 Person id,name



我经常有这样的疑问:

  select * from Person where name Like%abc%。 

我有两个问题:


  1. 如何使用代码优先5(CTP5)实现此查询

  2. 如何在名称列中添加索引,以便根据名称更快地进行数据检索在查询中?


解决方案

像运算符可以使用Contains函数执行:

  var query = from p in context.Persons 
其中p.Name.Contains(abc)
select p ;

索引必须由SQL添加 - EF中没有特殊的结构来创建索引。您可以从DB初始化执行此SQL。



首先,您必须实现自定义初始化程序:

 code> public class MyInitializer:CreateDatabaseIfNotExists< MyContext> 
{
protected override void Seed(MyContext context)
{
context.Database.SqlCommand(CREATE INDEX IX_Person_Name ON Person(Name));
}
}

然后你必须注册新的初始化器:

  DbDatabase.SetInitializer< MyContext>(new MyInitializer()); 


I have a table Person: id, name

I often have queries like:

select * from Person where name Like "%abc%".

I have 2 questions:

  1. How do I implement this query using code-first 5 (CTP5)
  2. How do I add an index on the name column to make data retrieval faster based on name like in the query?

解决方案

Like operator can be performed with Contains function:

var query = from p in context.Persons
            where p.Name.Contains("abc")
            select p;

Index must be added by SQL - there is no special construction in EF to create index. You can execute this SQL from DB initialization.

First you must implement custom initializer:

public class MyInitializer : CreateDatabaseIfNotExists<MyContext>
{
  protected override void Seed(MyContext context)
  {
    context.Database.SqlCommand("CREATE INDEX IX_Person_Name ON Person (Name)");
  }
}

Then you must register new initializer:

DbDatabase.SetInitializer<MyContext>(new MyInitializer());

这篇关于向表添加索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆