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

17

我有一个表格(Id,name,itemst,otherproperties),其中Id是主键,我想创建一个唯一的复合键(name,itemst)。我如何通过Code First添加此内容,可以使用Fluent API(首选)或注释?

2个回答

23

假设你有一个名为的实体

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

}

您可以使用复合键创建

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

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

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

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

}

1
嘿!我正准备回答那个问题。 - User 12345678
@ByteBlast 啊!太棒了你在这里,部分答案仍然缺失,通过流畅的 API 添加唯一值 - Parimal Raj

16
这里有一个示例,展示了如何通过流畅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}));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接