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 ?.