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) ?
Asked
Active
Viewed 1,629 times
1
-
Cross-posted as https://github.com/npgsql/efcore.pg/issues/1483 – Shay Rojansky Sep 01 '20 at 19:58
1 Answers
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