How to create index in Entity Framework 6.2 with code first

ef-code-first entity-framework entity-framework-6

Accepted Answer

Entity Framework 6.2 was formally published on October 26, 2017. It has a possibility to make index definitions simple using the Fluent API. In the 6.2 beta, how to utilize it was already announced.

You may now utilize theHasIndex() methodology, thenIsUnique() if it ought to be a special index.

Here's a quick before-and-after comparison example:

// before 
modelBuilder.Entity<Person>()
        .Property(e => e.Name)
        .HasColumnAnnotation(
            IndexAnnotation.AnnotationName, 
            new IndexAnnotation(new IndexAttribute { IsUnique = true }));

// after
modelBuilder.Entity<Person>()
    .HasIndex(p => p.Name)
    .IsUnique();

// multi column index
modelBuilder.Entity<Person>()
    .HasIndex(p => new { p.Name, p.Firstname })
    .IsUnique();

The index can also be labeled as clustered using.IsClustered() .


EDIT #1

A multi-column index example and more details on how to label an index as clustered have been included.


EDIT #2

In addition, it is precisely the same in EF Core 2.1 as it is right now in EF 6.2.
The MS Doc article used as a reference is Here.

84
12/10/2018 7:39:20 AM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow