Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Property unique in EF6 code first [duplicate]

I have this class:

public class BSC
{
    public int BSCId { get; set; }

    public string BSCName { get; set; }
}

and the config class:

public class BSCConfig :EntityTypeConfiguration<BSC>
{
    public BSCConfig()
    {
        Property(m => m.BSCName).HasMaxLength(50).HasColumnName("Category").IsRequired();

    }
}

I want to make this property Unique, but I do not have isUnique or Index method.

Can you please tell me how to make this property Unique?

like image 868
Lucian Bumb Avatar asked Aug 30 '15 10:08

Lucian Bumb


2 Answers

Use HasColumnAnnotation :

Property(m => m.BSCName).HasMaxLength(50).HasColumnName("Category").IsRequired()
  .HasColumnAnnotation("Index",
   new IndexAnnotation(new IndexAttribute("IX_X_Category") { IsUnique = true }));
like image 67
Taher Rahgooy Avatar answered Sep 28 '22 16:09

Taher Rahgooy


You can also do it with data annotations.

[Index("IX_X_Category", 1, IsUnique = true)]
public string BSCName { get; set; }
like image 33
Hezye Avatar answered Sep 28 '22 14:09

Hezye