How to create index in Entity Framework 6.2 with code first

前端 未结 10 486
不知归路
不知归路 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条回答
  •  情书的邮戳
    2020-11-29 20:03

    I write an extension method for use in fluent EF to avoid extra code:

    public static PrimitivePropertyConfiguration HasIndexAnnotation(
        this PrimitivePropertyConfiguration primitivePropertyConfiguration, 
        IndexAttribute indexAttribute = null
        )
    {
        indexAttribute = indexAttribute ?? new IndexAttribute();
    
        return primitivePropertyConfiguration
            .HasColumnAnnotation(
                IndexAnnotation.AnnotationName, 
                new IndexAnnotation(indexAttribute)
            );
    }
    

    then use it like this:

    Property(t => t.CardNo)
        .HasIndexAnnotation();
    

    or like this if index needs some configs:

    Property(t => t.CardNo)
        .HasIndexAnnotation(new IndexAttribute("IX_Account") { IsUnique = true });
    

提交回复
热议问题