I'd like to add unique constraint using model builder in ASP.NET Core
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.
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:

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