1

The solution of Does EF Core allow a unique column to contain multiple nulls? works perfect with Microsoft SQL Server but not with PostgreSQL. Is there a solution which works also with PostgreSQL (Npgsql provider) ?

alc
  • 97
  • 1
  • 1
  • 6

1 Answers1

1

You can simply use a filtered index to specify the WHERE clauses as you wish:

modelBuilder.Entity<Blog>().HasIndex(b => b.SomeInt)
    .HasFilter(@"""SomeInt"" IS NOT NULL")
    .IsUnique();

This creates the index as follows:

CREATE UNIQUE INDEX "IX_Blogs_SomeInt" ON "Blogs" ("SomeInt") WHERE "SomeInt" IS NOT NULL;
Shay Rojansky
  • 15,357
  • 2
  • 40
  • 69
  • +1 - Filtered indexes were the way to do this in PostGres 14 Note there is a new [NULLS NOT DISTINCT](https://stackoverflow.com/a/8289253/) alternative in 15+ – StuartLC Dec 16 '22 at 17:04