简体   繁体   English

关键和必需数据注释

[英]Key and Required data annotations

When using the entity framework there are the following data annotations: 使用实体框架时,有以下数据注释:

Just for reference, I using the definitions from this wiki article : 仅供参考,我使用此Wiki文章中的定义:

Primary Key 首要的关键

  1. A primary key cannot allow null values. 主键不能允许空值。 (You cannot define a primary key on columns that allow nulls.) (您不能在允许为空的列上定义主键。)
  2. Each table can have at most one primary key. 每个表最多可以有一个主键。

Unique Key 唯一键

  1. A unique key can allow null values. 唯一键可以允许空值。 (You can define a unique key on columns that allow nulls.) (您可以在允许空值的列上定义唯一键。)
  2. Each table can have multiple unique keys. 每个表可以具有多个唯一键。

Is the KeyAttribute used to denote a primary key or is it used to denote a unique key? KeyAttribute用于表示主键还是用于表示唯一键?

When using annotations would the following be considered reduntant or necessary? 使用注释时,以下内容是否被认为是多余的或必要的?

class Example
{
    [Required(), Key()]
    public int Id { get; set; }
    ...
}

In your example, that would be redundant as your models require a key value to uniquely identify them once they have been annotated with Key . 在您的示例中,这将是多余的,因为一旦模型被Key注释,模型就需要一个键值来唯一地标识它们。

And as an aside, if you are using Code-First, even Key would be redundant as by convention a property called Id or ModelNameId would be used for your primary key. ModelNameId一句,如果您使用的是Code-First,则即使Key也是多余的,因为按照惯例,称为IdModelNameId的属性将用作主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM