EF Core - Add Unique Constraint

Viewed 1149

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.

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

Related