如何使用EF 6 Fluent Api添加复合唯一键?

Bar*_*tta 15 c# entity-framework

我有一个表(Id,name,itemst,otherproperties),Id是主键,我想要一个唯一的复合键(name,itemst).如何使用代码首先通过流畅的API(首选)或注释添​​加此代码?

PaR*_*RaJ 19

假设您有一个名为的实体

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

}
Run Code Online (Sandbox Code Playgroud)

您可以使用创建复合键

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});
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢数据注释,则可以简单地添加KeyAttribute到多个属性

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

    [DatabaseGenerated(DatabaseGeneratedOption.None)]   // optional
    [Key]
    public String Name { get; set; }

}
Run Code Online (Sandbox Code Playgroud)


Bar*_*tta 12

下面是一个示例,说明如何通过流畅的API创建复合唯一键.复合键由ProjectId和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}));
}
Run Code Online (Sandbox Code Playgroud)