0

Is there a way to specify a multi-column uniqueness constraint using Entity Framework?

This is the constraint I want

CREATE UNIQUE NONCLUSTERED INDEX myconstraint
ON myTable(col1,col2)
WHERE col2 IS NOT NULL;

The code below gets me most of the way in Entity Framework Fluent API but falls short because it doesn't allow nulls (ie, two nulls in col2 will be considered a violation of the constraint, whereas I want it to allow multiple nulls).

modelBuilder.Entity<myTable>().Property(x => x.col1)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
    new IndexAnnotation(new IndexAttribute("myconstraint", 0) { IsUnique = true }));
modelBuilder.Entity<myTable>().Property(x => x.col2)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
    new IndexAnnotation(new IndexAttribute("myconstraint", 1) { IsUnique = true }));
Matthew
  • 4,149
  • 2
  • 26
  • 53

0 Answers0