Search code examples
entity-frameworkasp.net-coreconstraintsunique

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.


Solution

  • 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