Entity Framework 核心 - 防止唯一索引出现多个空值
Entity Framework Core - prevent multiple null values on unique indexes
关于这个问题:
我希望每个值都是唯一的,即使是 null。
config.Entity<Product>()
.HasIndex(b => b.ProductId)
.IsUnique();
SQL 中的等价物有效
[ProductId] int null unique foreign key references Product([Id])
我可以修改此代码以防止列上出现多个空值吗?
默认情况下,EF Core 的 Fluent API 添加
filter: "[ProductId] IS NOT NULL"
到迁移中创建的索引。
为了确保即使是NULL也是唯一的,我们必须修改我们的索引,像这样:
config.Entity<Product>()
.HasIndex(b => b.ProductId)
.IsUnique()
.HasFilter(null);
这将删除过滤器,并允许 NULL 是唯一的。
关于这个问题:
我希望每个值都是唯一的,即使是 null。
config.Entity<Product>()
.HasIndex(b => b.ProductId)
.IsUnique();
SQL 中的等价物有效
[ProductId] int null unique foreign key references Product([Id])
我可以修改此代码以防止列上出现多个空值吗?
默认情况下,EF Core 的 Fluent API 添加
filter: "[ProductId] IS NOT NULL"
到迁移中创建的索引。
为了确保即使是NULL也是唯一的,我们必须修改我们的索引,像这样:
config.Entity<Product>()
.HasIndex(b => b.ProductId)
.IsUnique()
.HasFilter(null);
这将删除过滤器,并允许 NULL 是唯一的。