Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core - Add Unique Constraint

I'd like to add unique constraint using model builder in ASP.NET Core

  • .NET 5
  • EF Core 5..

Here is what I found:

        modelBuilder.Entity<Ticker>()
            .HasIndex(r => r.Name)
            .IsUnique();

However after updating database it adds index instead of constraint. Is there the way to add constraint? Thanks for the answer.

like image 988
Arcadio1729 Avatar asked Jul 27 '26 04:07

Arcadio1729


1 Answers

Although you use .HasIndex(r => r.Name).IsUnique(),it will create a unique Index instead of Constraint. But the effect are the same. It will prevent you adding duplicated value for Name.

However after updating database it adds index instead of constraint. Is there the way to add constraint?

If you must add Constraint, I suggest you use HasAlternateKey method which enables you to create an alternate key by placing a unique constraint:

modelBuilder.Entity<Ticker>()
           .HasAlternateKey(r => r.Name);

Then you can see it adds the unique constraint like below in database:

enter image description here

like image 154
Rena Avatar answered Jul 28 '26 16:07

Rena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!