身份规范设置为false [英] Identity specification set to false
问题描述
我正在使用 EF5
和 Code First
创建数据库。当实体具有 Id字段
时,EF在数据库中创建诸如主键
之类的字段,并设置 Identity规范
到 true
(自动生成的值)。如何将身份规范默认设置为false
?
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
?
推荐答案
如果您不想使用身份密钥,则有几种选择。
If you don't want to use identity keys you have several options.
选项1::您可以通过删除 StoreGeneratedIdentityKeyConvention
来全局关闭此功能:
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.
选项2:属性:
public class MyEntity {
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
}
选项3: Fluent API:
Option 3: Fluent API:
public class YourContext : DbContext {
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<MyEntity>()
.Property(e => e.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
}
这篇关于身份规范设置为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!