EF Code First Fluent API Defines Unique Constraint

I am trying to force the use of a unique column constraint, using an empty configuration for the code first. Is there a better way than implementing it in business logic or using something like below

context.ObjectContext.ExecuteStoreCommand("CREATE UNIQUE CONSTRAINT...");

Or was I wondering if it is not possible to implement a unique constraint using smooth configurations?

EDIT:

This has confirmed that this is not possible with smooth configurations. But again, I wonder how best to do this? And I would like to know why EF does not support this.

+5
source share
4 answers

I had this problem before

it cannot implement a unique constraint using a free API.

, , , !

+1

This is possible with DbMigrations ...

public override void Up()
{
    CreateIndex("dbo.MyTableName", "MyColumnName", unique: true); 
}
+1
source

This can be done using a special extension method:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;

internal static class TypeConfigurationExtensions
{
    public static PrimitivePropertyConfiguration HasUniqueIndexAnnotation(
        this PrimitivePropertyConfiguration property, 
        string indexName,
        int columnOrder = 0)
    {
        var indexAttribute = new IndexAttribute(indexName, columnOrder) { IsUnique = true };
        var indexAnnotation = new IndexAnnotation(indexAttribute);

        return property.HasColumnAnnotation("Index", indexAnnotation);
    }
}

See the full answer here: fooobar.com/questions/36758 / ...

+1
source

All Articles