Creating Unique Index with Entity Framework 6.1 fluent API

后端 未结 6 645
醉话见心
醉话见心 2020-12-08 18:49

I have a column \"Name\" that must be unqiue. No foreign key or anything like that.

EF 6.1 finally supports creating such indexes via Annotations. That has been disc

6条回答
  •  不知归路
    2020-12-08 19:38

    This answer contains only additional information as there are already great answers.

    If you want to have multiple unique fields in your index, you can achieve it by adding the Order property. You must also make sure that you use the same index name in all your properties (see uniqueIndex below).

    string uniqueIndex = "UN_TableName";
    
    this.Property(t => t.PropertyOne)
        .HasColumnAnnotation(
            IndexAnnotation.AnnotationName,
            new IndexAnnotation(
                new IndexAttribute(uniqueIndex)
                {
                    IsUnique = true,
                    Order = 1
                }
            )
        );
    
    this.Property(t => t.PropertyTwo)
        .HasColumnAnnotation(
            IndexAnnotation.AnnotationName,
            new IndexAnnotation(
                new IndexAttribute(uniqueIndex)
                {
                    IsUnique = true,
                    Order = 2
                }
    
            )
        );
    

    Now, let's say you also want an index on PropertyTwo.

    The wrong way of doing it would be to start a new line with this.Property(t => t.PropertyTwo) as it would CANCEL your unique index.

    All your indexes (index and unique) must be defined at the same time. This would be the right way to do it :

    this.Property(t => t.PropertyTwo)
        .HasColumnAnnotation(
            IndexAnnotation.AnnotationName,
            new IndexAnnotation(new[] 
                {
                    new IndexAttribute(), // This is the index
                    new IndexAttribute(uniqueIndex) // This is the Unique made earlier
                    {
                        IsUnique = true,
                        Order = 2
                    }
                }
            )
        );
    

    Finally, if you also want to change the sort order of your index/unique, you can see :

    How to add an index on multiple columns with ASC/DESC sort using the Fluent API ?.

提交回复
热议问题