[英]Case insensitive unique constraint for Postgres + EF Core
I am using Postgres + EF Core.我正在使用 Postgres + EF Core。 I have a column called Name which I want to be unique.我有一个名为 Name 的列,我希望它是唯一的。 I have tried the following:我尝试了以下方法:
builder.HasIndex(s => s.Name).IsUnique();
but this allows "test123" and "TEST123" to be accepted.但这允许接受“test123”和“TEST123”。 How can I add a case insensitive unique constraint with fluent api?如何使用流畅的 api 添加不区分大小写的唯一约束?
Or do I just need to create a NormalizedName column and add the unique constraint to that.还是我只需要创建一个 NormalizedName 列并向其中添加唯一约束。 Seems like a lot of work every time I want to add a unique constraint to a column.每次我想向列添加唯一约束时,似乎需要做很多工作。
If you're using EF Core 5.0, then see below (probably the better solution).如果您使用的是 EF Core 5.0,请参见下文(可能是更好的解决方案)。 Otherwise, I added a case insensitive check by making use of the citext
extension as described here .否则,我通过使用此处所述的citext
扩展名添加了不区分大小写的检查。 There are some limitations, I won't list them here but you can read up on them in the previous link or directly on the PostgreSQL Docs .有一些限制,我不会在这里列出它们,但您可以在上一个链接中阅读它们或直接在PostgreSQL Docs上阅读它们。
Also ensure you have the postgres-contrib
package installed to make use of this extension.还要确保您安装了postgres-contrib
package 以使用此扩展。
First, enable the extension by adding it to your model builder首先,通过将扩展添加到 model 构建器来启用扩展
modelBuilder.HasPostgresExtension("citext");
Then use the citext
as the column type然后使用citext
作为列类型
builder.Property(s => s.Name)
.HasColumnType("citext")
With EF Core 5.0 there's better support by making use of Collations .使用 EF Core 5.0 可以通过使用Collations获得更好的支持。 You can also check out the Npgsql docs in regards to PostrgeSQL.您还可以查看有关 PostrgeSQL 的Npgsql 文档。 This gets over a bunch of limitations with citext
above and gives you a lot more control.这克服了上面citext
的一系列限制,并为您提供了更多控制权。
So the (untested) steps are:所以(未经测试的)步骤是:
modelBuilder.HasCollation("case_insensitive_collation", locale: "en-u-ks-primary", provider: "icu", deterministic: false);
builder.HasIndex(s => s.Name)
.UseCollation("case_insensitive_collation")
.IsUnique();
If you achieved it some other way, I'd love to hear how.如果你以其他方式实现它,我很想听听如何。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.