Entity Framework: Add Unique Constraint to existing property

entity-framework entity-framework-core

Question

I have an existing model, SomeModel, which contains a property Prop. I'd like to enforce that the values of Prop be unique.

To this end, I'm adding the following to my model:

public static void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeModel>()
      .HasAlternateKey(a => a.Prop);
}

but ef migrations isn't picking up the change.

How can I correct this?

1
0
9/17/2018 2:29:45 PM

Popular Answer

This works for me with EF Core on an already existing model. add-migration picks up the change.

public static void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeModel>()
                .HasIndex(u => u.Prop)
                .IsUnique();
}
1
9/20/2018 7:07:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow