EntityFramework 7 and Unique constraint (Data Annotations or Fluid)

entity-framework-core unique-constraint

Question

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

Accepted Answer

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://docs.microsoft.com/en-us/ef/core/modeling/alternate-keys


Popular Answer

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();
        });
    }


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why