How to create index in Entity Framework 6.2 with code first

前端 未结 10 473
不知归路
不知归路 2020-11-29 19:16

Is there a way to create an index on a property/column using code-first, instead of using the new IndexAttribute ?

10条回答
  •  Happy的楠姐
    2020-11-29 20:00

    Currently there is no "first class support" for creating a index via the fluent API, but what you can do is via the fluent API you can mark properties as having attributes from the Annotation API. This will allow you to add the Index attribute via a fluent interface.

    Here are some examples from the work item from Issues site for EF.

    Create a index on a single column:

    modelBuilder.Entity()
        .Property(e => e.MyProperty)
        .HasColumnAnnotation(
            IndexAnnotation.AnnotationName, 
            new IndexAnnotation(new IndexAttribute()));
    

    Multiple indexes on a single column:

    modelBuilder.Entity()
        .Property(e => e.MyProperty)
        .HasColumnAnnotation(
            IndexAnnotation.AnnotationName, 
            new IndexAnnotation(new[]
                {
                    new IndexAttribute("Index1"),
                    new IndexAttribute("Index2") { IsUnique = true }
                }));
    

    Multi-Column indexes:

    modelBuilder.Entity()
        .Property(e => e.MyProperty1)
        .HasColumnAnnotation(
            IndexAnnotation.AnnotationName,
            new IndexAnnotation(new IndexAttribute("MyIndex", 1)));
    
    modelBuilder.Entity()
        .Property(e => e.MyProperty2)
        .HasColumnAnnotation(
            IndexAnnotation.AnnotationName, 
            new IndexAnnotation(new IndexAttribute("MyIndex", 2)));
    

    Using the above techniques will cause .CreateIndex() calls to be automatically created for you in your Up() function when you scaffold your next migration (or be automatically created in the database if you are not using migrations).

提交回复
热议问题