开发者

Adding index to a table

开发者 https://www.devze.com 2023-02-12 02:07 出处:网络
I have a table Person: id, name I often have queries like: select * from Person where name Like \"%abc%\".

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开发者_JS百科 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());


in EF 6 you can create indexes like this

   Property(t => t.TotalValue)
            .HasColumnAnnotation(
                IndexAnnotation.AnnotationName,
                new IndexAnnotation(new IndexAttribute("IX_inventory_import_total_value", 1))
            );
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号