【问题标题】:How to add a composite unique key using EF 6 Fluent Api?如何使用 EF 6 Fluent Api 添加复合唯一键?
【发布时间】:2014-08-22 18:32:05
【问题描述】:

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

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    假设您有一个名为

    的实体
    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; }
    
    }
    

    【讨论】:

    • 嘿!我正要回答这个问题。
    • @ByteBlast 啊! gr8 2 你在这里,ans 的一部分仍然丢失,通过 fluent api 添加独特
    【解决方案2】:

    这是一个示例,展示了如何通过 fluent 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}));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-28
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多