0

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?

3
  • Add proper steps Commented Sep 17, 2018 at 14:53
  • Are you using fluent API or Annotations? Commented Sep 18, 2018 at 6:43
  • This may be helpful. stackoverflow.com/questions/23892553/… Commented Sep 18, 2018 at 7:12

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

I've found that this override only works if it's there when you first create the model - not if you add it at some later point.
Hmm, you are using EF Core, correct (inferred from the tag)? I just tested it on an existing model in one of my projects, and this picked it up just fine. Maybe it depends on your EF provider? My example: github.com/collinbarrett/FilterLists/commit/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.