Identity specification set to false

六眼飞鱼酱① 提交于 2020-01-21 06:51:00

问题


I am using EF5 and Code First to create database. When Entity has Id field, EF create such field as Primary Key in database and set Identity specification to true(auto generated value). How to set Identity specification to false by default?


回答1:


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


来源:https://stackoverflow.com/questions/14829911/identity-specification-set-to-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!