Adding an index to a table

I have a table Person : id, name

I often get queries like:

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

I have 2 questions:

  • How to implement this request using code-first 5 (CTP5)
  • How do I add an index to a name column to speed up data retrieval based on a name like a query?
+9
entity-framework entity-framework-ctp5
Feb 18 '11 at 11:35
source share
2 answers

A similar statement can be performed using the Contains function:

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

An index must be added by SQL - there is no special construct in EF to create an index. You can execute this SQL with DB initialization.

First you must implement a 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 a new initializer:

 DbDatabase.SetInitializer<MyContext>(new MyInitializer()); 
+22
Feb 18 '11 at 12:23
source share

in EF 6 you can create such indexes

  Property(t => t.TotalValue) .HasColumnAnnotation( IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_inventory_import_total_value", 1)) ); 
0
Jul 31 '17 at 13:32
source share



All Articles