How to add a composite unique key using EF 6 Fluent Api?

c# entity-framework

Question

I have a table (Id, name, itemst, otherproperties), Id is the primary key and I want a unique composite key (name, itemst). How can I add this using code first either by fluent API (preferred) or annotation?

1
15
7/2/2014 4:53:50 AM

Accepted Answer

Here is an example showing how to create a composite unique key via fluent API. The composite key consists of ProjectId and SectionOdKey.

public class Table
{
    int Id{set;get;}    
    int ProjectId {set;get;}
    string SectionOdKey{set;get;}
}

public class TableMap : EntityTypeConfiguration<Table>
{
   this.Property(t => t.ProjectId).HasColumnName("ProjectId")
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 1){IsUnique = true}));
   this.Property(t => t.SectionOdKey).HasColumnName("SectionOdKey")
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 2){IsUnique = true}));
}
13
7/4/2014 9:01:26 AM

Popular Answer

Let say you have a entity named

public class MyTable
{
    public int Id {get; set;}
    public String Name {get; set;}

}

you can create composite key using

public class YourContext : DbContext
{
    public DbSet<MyTable> MyTables { get; set; }

    protected override void OnModelCreating(DbModelBuilder builder)
    {
        builder.Entity<MyTable>().HasKey(table => new {table.Id, table.Name});
    }
}

if you prefer data annotation you can simple add KeyAttribute to multiple properties

public class MyTable
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  // optional
    [Key]
    public int Id { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.None)]   // optional
    [Key]
    public String Name { 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