身份规范设置为false [英] Identity specification set to false

查看:82
本文介绍了身份规范设置为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆