EF Core是否允许过滤/部分唯一索引不允许多个NULL?

时间:2017-05-14 09:19:52

标签: c# entity-framework ef-code-first entity-framework-core

EF Core allows一个包含多个NULL的唯一(已过滤)索引。

我可以将其配置为不允许多个NULL吗?

假设我已经在属性Column1Column2Column3上定义了唯一索引:

config.Entity<Product>()
    .HasIndex("Column1", "Column2", "Column3")
    .IsUnique();

一个例子:

Id   Column1   Column2   Column3
1    100       "foo"     "bar"    // unique
2    100       "foo"     "bar"    // not allowed (dupe)
3    100       NULL      "bar"    // allowed
4    100       NULL      "bar"    // allowed - but I want this to fail
5    100       NULL      "bar"    // allowed - but I want this to fail
6    100       NULL      "bar"    // allowed - but I want this to fail

这就是我想要的:

  • Row1唯一
  • Row2失败(唯一约束违规),因为它是row1
  • 的欺骗
  • 允许Row3,因为它与row1
  • 不同
  • Row4 / 5/6必须失败,因为它们是row3的欺骗

但是第4/5/6行不会失败。

1 个答案:

答案 0 :(得分:0)

我正在使用索引中的SQLite which excludes NULLs

迁移产生了这个:

CREATE UNIQUE INDEX [IX_Product] ON [Product] 
([Column1Id] ASC, [Column2Id] ASC, [Column3Id] ASC);

因此,在迁移课程中,我将其删除,并将其替换为Sql("...")调用:

CREATE UNIQUE INDEX [IX_Product] ON [Product] 
(COALESCE([Column1Id],"") ASC, COALESCE([Column2Id],"") ASC, COALESCE([Column3Id],"") ASC);

现在它强制执行NULL的唯一性。

(我在SQLite上测试了这个,不确定SQL Server。)

相关问题