简体   繁体   中英

Entity Framework unique key with fluent api?

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);   
    }
}

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}));

     }
}

I guess you can use IndexAttribute :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM