iDipa
iDipa

Reputation: 345

Entity Framework 6.1.3 :Set unique key constraint to a column

I am using latest version of Entity Framework with a code-first approach in my application which I develop in VS2015.

In my one of the entity sets (Customer), I want to set a unique key constraint on column EmailAddress.

I have tried this:

[Index("IX_EmailAddress", 1, IsUnique = true)]

but it is not working. In the Customer table, the column EmailAddress should have only unique values, it should allow duplicates.

Please guide me for it.

Thank you.

Upvotes: 1

Views: 1635

Answers (1)

Georg Patscheider
Georg Patscheider

Reputation: 9463

We are using the following extension method:

/// <summary>
/// Method to add a unique constraint to a property of an entity.
/// The unique constraint name is usually "UI_{classname}_{propertyname}".
/// </summary>
/// <param name="prop">The property for which a unique constraint is added</param>
/// <param name="constraintName">The name of the constraint</param>
/// <param name="constraintOrder">
///     Optional constraint order for multi column constraints.
///     This can be used if <see cref="HasUniqueConstraint"/> is called for multiple properties to define the order of the columns.
/// </param>
public static void HasUniqueConstraint(this PrimitivePropertyConfiguration prop, string constraintName, int constraintOrder = 1) {
    prop.HasColumnAnnotation(IndexAnnotation.AnnotationName,
        new IndexAnnotation(new IndexAttribute(constraintName, constraintOrder) {
            IsUnique = true
        })
    );
}

And we call it in the ModelBuilder as follows:

 ModelBuilder.Entity<Customer>().Property(c => c.EmailAddress ).HasUniqueConstraint("IX_EmailAddress");

But I am not sure if this is different form the attribute you have used. Anyhow, after applying this, you should see the following statement in the resulting migration:

 CreateIndex("dbo.Customer", "EmailAddress ", unique: true, name: "IX_EmailAddress");

Upvotes: 2

Related Questions