[英]How do you add a Unique case insensitive Index to a PostgresSQL table using EF Fluent API
我最近一直在使用 PostgreSQL 而不是 SQL,所以发现两者之间有很多细微差别。
我希望能够使表中的字符串值唯一,因此首先使用 EF 代码流利 API,我有这段代码。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyTable>()
.HasIndex(u => u.UniqueValue)
.IsUnique();
base.OnModelCreating(modelBuilder);
}
创建迁移时,它会生成这个。
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateIndex(
name: "IX_MyTable_UniqueValue",
table: "MyTable",
column: "UniqueValue",
unique: true);
}
然后,这会将索引添加到 PostgreSQL 表中,并在单词大小写相同时起作用。
例如,尝试插入“Hello”两次,但它不起作用。
它确实允许单词的变体,所以我可以插入“Hello”、“HEllo”、“HELlo”等...
看起来可以使用类似的方法在 PostgreSQL 中的索引上强制大小写
CREATE UNIQUE INDEX UniqueValue ON MyTable (UPPER(UniqueValue));
但是我不确定如何通过 EF Fluent API 执行此操作并从中创建迁移?
看起来现在你必须设置一个原始的 SQL 迁移。 对此的支持仍未添加(尚未)。 您还可以设置一个生成的(计算的)列来保存upper(UniqueValue)
的结果,然后在其上添加一个唯一索引。
无法添加基于表达式的唯一约束或将表达式添加到现有的唯一索引键。 您可以按原样使用您的定义构建新索引:
CREATE UNIQUE INDEX UniqueValue ON MyTable (UPPER(UniqueValue));
或者添加一个排除约束,它最终会做几乎相同的事情(截至目前,EF 还远未支持):
create table test(txt text);
alter table test
add constraint case_insensitive_unique
exclude using gist(upper(txt) with =);
insert into test(txt) select 'hello';
--INSERT 0 1
insert into test(txt) select 'Hello';
--ERROR: conflicting key value violates exclusion constraint "case_insensitive_unique"
--DETAIL: Key (upper(txt))=(HELLO) conflicts with existing key (upper(txt))=(HELLO).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.