Identity specification set to false

后端 未结 1 497
有刺的猬
有刺的猬 2021-01-12 05:19

I am using EF5 and Code First to create database. When Entity has Id field, EF create such field as Primary Key in databa

相关标签:
1条回答
  • 2021-01-12 06:10

    If you don't want to use identity keys you have several options.

    Option 1: You can globally turn off this feature by removing StoreGeneratedIdentityKeyConvention:

    public class YourContext : DbContext {
        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            modelBuilder.Conventions.Remove<StoreGeneratedIdentityKeyConvention>();
        }
    }
    

    You can selectively select keys and change the behavior for them by either applying attribute or fluent mapping.

    Option 2: Attribute:

    public class MyEntity {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Id { get; set; }        
    }
    

    Option 3: Fluent API:

    public class YourContext : DbContext {
        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            modelBuilder.Entity<MyEntity>()
                        .Property(e => e.Id)
                        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }
    }
    
    0 讨论(0)
提交回复
热议问题