实体框架核心 - 防止唯一索引上的多个空值

ser*_*0ne 5 c# entity-framework unique-constraint entity-framework-core

关于这个问题:EF Core是否允许一个唯一的列包含多个空值?

我希望每个值都是唯一的,甚至是null.

config.Entity<Product>()
    .HasIndex(b => b.ProductId)
    .IsUnique();
Run Code Online (Sandbox Code Playgroud)

SQL中的等价物有效

[ProductId] int null unique foreign key references Product([Id])
Run Code Online (Sandbox Code Playgroud)

我可以修改此代码以防止列上出现多个空值吗?

ser*_*0ne 13

默认情况下,EF Core的Fluent API会添加

filter: "[ProductId] IS NOT NULL"
Run Code Online (Sandbox Code Playgroud)

到迁移中创建的索引.

为了确保偶数NULL是唯一的,我们必须修改索引,如下所示:

config.Entity<Product>()
    .HasIndex(b => b.ProductId)
    .IsUnique()
    .HasFilter(null);
Run Code Online (Sandbox Code Playgroud)

这将删除过滤器,并允许NULL是唯一的.