Reputation: 2089
I have been searching the net for a way to create a unique constraint using code first with data annotion or with the Fluid API for Entityframework 7.. is this not implemented yet or how come I cant find any information regarding this? Any ideas of how to create such a constraint using code first and EF7? Is there anyway to in the end of my OnModelCreating to execute a SQL-script to "manually" create the constraint while Im waiting for a more "solid" way of doing this?
Br, Inx
Upvotes: 3
Views: 917
Reputation: 41759
You can use Alternate keys:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>()
.HasAlternateKey(c => c.LicensePlate);
}
They are enforced via Unique indexes is SQL Server, see https://learn.microsoft.com/en-us/ef/core/modeling/alternate-keys
Upvotes: 2
Reputation: 12425
I believe you can do this using the fluent API, I haven't found a DataAnnotation yet though.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityClass>(entity =>
{
entity.HasIndex(e => e.Index).IsUnique();
});
}
Upvotes: 3