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

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

假设您有一个名为的实体

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

您可以使用创建复合键

 public class YourContext : DbContext { public DbSet MyTables { get; set; } protected override void OnModelCreating(DbModelBuilder builder) { builder.Entity().HasKey(table => new {table.Id, table.Name}); } } 

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

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

下面是一个示例,说明如何通过流畅的API创建复合唯一键。 复合键由ProjectId和SectionOdKey组成。

 public class Table { int Id{set;get;} int ProjectId {set;get;} string SectionOdKey{set;get;} } public class TableMap : EntityTypeConfiguration { 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})); }