数据库生成(DatabaseGeneratedOption.Identity)与密钥 [英] DatabaseGenerated(DatabaseGeneratedOption.Identity) vs Key

查看:25
本文介绍了数据库生成(DatabaseGeneratedOption.Identity)与密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先看代码,看到一些使用[DatabaseGenerated(DatabaseGeneratedOption.Identity)]表示主键的例子,还有一些使用[Key]的例子.

Looking at code first, I see some examples that use [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to denote a primary key, and other examples that use [Key].

我无法找到有关两者比较的描述.

I haven't been able to find a description of how the two compare.

有人可以告诉我何时/如果我想使用一个而不是另一个吗?

Can someone tell me when/if I'd want to use one over the other?

推荐答案

一个指定显式 Primary Key ,另一个指定它应该是该数据库中的标识字段(这取决于提供者).在很多情况下,Key 将是一个身份字段.

One specifies an explicit Primary Key , the other specifies that it should be an identity field in that database (which depends on the provider). In a lot of cases, the Key will be an identity field.

DatabaseGeneratedOption.Identity

您可以使用 DatabaseGeneratedOption.Identity 选项将非键(非 ID)属性标记为数据库生成的属性.这指定属性的值将由数据库在 INSERT 语句中生成.无法更新此身份属性.

You can mark the non-key (non-id) properties as DB-generated properties by using the DatabaseGeneratedOption.Identity option. This specifies that the value of the property will be generated by the database on the INSERT statement. This Identity property cannot be updated.

请注意,数据库生成 Identity 属性值的方式取决于数据库提供者.它可以是身份、行版本或 GUID.SQL Server 为整数属性创建标识列.

Please note that the way the value of the Identity property will be generated by the database depends on the database provider. It can be identity, rowversion or GUID. SQL Server makes an identity column for an integer property.

关键属性

Key 属性可以应用于实体类中的属性以使其成为主键的键属性和对应的列数据库中的列.默认约定创建一个主键名称为 Id 或 Id 的属性的列.这键属性会覆盖此默认约定.

The Key attribute can be applied to a property in an entity class to make it a key property and the corresponding column to a PrimaryKey column in the database. The default convention creates a primary key column for a property whose name is Id or Id. The Key attribute overrides this default convention.

如果你想指定一个非身份主键,你可以使用这样的东西

if you wanted to specify a non identity primary key, you may use something like this

[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]

这篇关于数据库生成(DatabaseGeneratedOption.Identity)与密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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