【问题标题】:Does EF Core allow a filtered/partial unique index which does not allow multiple NULLs?EF Core 是否允许不允许多个 NULL 的过滤/部分唯一索引?
【发布时间】:2017-05-14 09:19:51
【问题描述】:

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

这就是我想要的:

  • 第 1 行唯一
  • Row2 失败(违反唯一约束),因为它是 row1 的欺骗
  • 允许第 3 行,因为它与第 1 行不同
  • 第 4/5/6 行必须失败,因为它们是第 3 行的骗子

但是 row4/5/6 不会失败。

【问题讨论】:

  • 您可以在迁移代码中将唯一索引更改为不被过滤(例如使用 .Sql() 方法
  • @ErikEJ 迁移生成:CREATE UNIQUE INDEX [IX_Column1_Column2_Column3] ON [Product] ([Column1Id] ASC,[Column2Id] ASC,[Column3Id] ASC); 如何将其更改为不过滤?
  • 这是您数据库中的索引吗?你可以编写脚本吗?
  • @ErikEJ 是的,这就是 EF Core 为我生成的。我想我已经想出了一个解决方案,我在下面添加了它......
  • 啊啊,你从来没有提到过 SQLite!完全不同的数据库引擎:-(

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


【解决方案1】:

我正在使用索引中的 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 不确定。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 2017-09-14
    • 2017-05-19
    • 1970-01-01
    • 2014-03-05
    • 2015-10-31
    • 2014-07-05
    • 1970-01-01
    相关资源
    最近更新 更多