Is it possible to set a unique constraint using Entity Framework Code First?

后端 未结 3 1948
我寻月下人不归
我寻月下人不归 2020-12-18 17:20

I want to enforce Unique constraint in a table & I am using Entity Framework Code-First.

Is it possible to add a unique constraint using EF 6 as i believe in ear

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 18:00

    Use this to define it in config class, if you're avoiding using annotations:

    public class YourTableConfig : EntityTypeConfiguration
    {
      public YourTableConfig()
      {
        ToTable("YourTableDbName");
    
        HasKey(u => u.Id);
    
        Property(c => c.CompanyId).HasColumnType("nvarchar").HasMaxLength(9).IsRequired();
    
        HasIndex(x => x.CompanyId).IsUnique(); // This sets the unique index
      }
    }
    

提交回复
热议问题