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

后端 未结 2 1701
予麋鹿
予麋鹿 2020-12-31 05:52

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 flu

2条回答
  •  春和景丽
    2020-12-31 06:23

    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 MyTables { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder builder)
        {
            builder.Entity().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; }
    
    }
    

提交回复
热议问题