How to set a Property unique in EF6 code first

c# entity-framework entity-framework-6

Question

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?

1
5
8/30/2015 10:54:30 AM

Accepted Answer

Use HasColumnAnnotation :

Property(m => m.BSCName).HasMaxLength(50).HasColumnName("Category").IsRequired()
  .HasColumnAnnotation("Index",
   new IndexAnnotation(new IndexAttribute("IX_X_Category") { IsUnique = true }));
4
8/30/2015 10:58:32 AM

Popular Answer

You can also do it with data annotations.

[Index("IX_X_Category", 1, IsUnique = true)]
public string BSCName { get; set; }


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