Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Unique Index with a Where clause with Entity Framework

I want to create a UNIQUE INDEX with a WHERE condition using Entity Framework.

public class Person {
    public string Name { get; set; }    

    public bool Expired { get; set; } 
}

The condition is that the Name is unique only when "Expired" is false.

The INDEX would look like this:

CREATE UNIQUE INDEX [IX_Person]
    ON Person(Name)
    WHERE [Expired] = 0;

Is there some way to write this unique index with code-first and not having to execute this SQL in a migration?

I can write this:

[Index("IX_Expired", IsUnique = true)]
public bool Expired { get; set; } 

But I don't find a way to specify the "WHERE" part.

like image 276
carraua Avatar asked Dec 07 '22 18:12

carraua


2 Answers

In case anyone comes here looking to do this in Entity Framework core.... you can now do it!

e.g. in your MigrationContext:

   builder.Entity<MyEntity>()
        .HasIndex(x => x.MyField)
        .HasFilter($"{nameof(MyEntity.MyField)} IS NOT NULL")
        .IsUnique();
like image 120
Mike Perrin Avatar answered Jan 07 '23 01:01

Mike Perrin


Is there some way to write this unique index with code-first and not having to execute this SQL in a migration?

No. EF can create basic indexes only.

EG for SQL Server, Filtered indexes, indexes with included columns, partitioned indexes, indexes on particular filegroups, indexes with row or page compression, Columnstore indexes, heap tables, memory-optimized tables, etc, can only be created using TSQL.

like image 29
David Browne - Microsoft Avatar answered Jan 07 '23 01:01

David Browne - Microsoft