Entity Framework unique key with fluent api?

c# entity-framework-6

Question

Is there any way to specify that an index should be unique using the Fluent API without adding it as a data annotation in the model itself?

public class RecordType
{
    public int Id { get; set; }

    [Index(IsUnique = true)]
    public string RecordType { get; set; }
}

How can I add the unique index in the code below?

public class RecordTypeConfiguration : EntityTypeConfiguration<RecordType>
{
    public RecordTypeConfiguration()
    {
       HasKey(i => i.Id);
       Property(e => e.RecordType).HasColumnType("VARCHAR").HasMaxLength(1);   
    }
}
1
1
9/18/2018 7:36:12 AM

Accepted Answer

In Entity Framework >= 6.2,

In DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Entity<RecordType>().HasIndex(u => u.RecordType).IsUnique();
}

In Entity Framework < 6.2

In DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Entity<RecordType>().Property(t => t.RecordType).HasMaxLength(1)
                                  .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("Ix_RecordType"){IsUnique = true}));
}

Or in a separate configuration file:

public class RecordTypeConfiguration : EntityTypeConfiguration<RecordType>
{
    public RecordTypeConfiguration()
    {
        HasKey(i => i.Id);

        Property(e => e.RecordType).HasColumnType("VARCHAR").HasMaxLength(1);

        Property(t => t.RecordType).HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("Ix_RecordType"){IsUnique = true}));

     }
}
3
8/28/2018 4:06:58 AM

Popular Answer

I guess you can use IndexAttribute :

   this.Property(t => t.RecordType)
   .HasColumnAnnotation(
   "Index",
   new IndexAnnotation(new IndexAttribute("_RecordType") { IsUnique = true }));


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