Search code examples
c#.net.net-coreentity-framework-coredbcontext

How to make fields unique in C# using EF Core?


I want to make a field unique in EF Core and I'm using .NET 5. I can't use the [Index(IsUnique = true)] attribute because if I try, I get an error. Maybe It's a part of EF but not EF Core.

How can I achieve this?

I've done several searches but I didn't find any suitable answer.


Solution

  • You can do like this.

    class MyContext: DbContext {
      public DbSet<Test> Tests { get; set; }
    
      protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity<Test>()
          .HasIndex(x => x.ColumnName)
          .IsUnique();
      }
    }