问题描述
我已经看到许多关于如何将字段标记为身份列的帖子和答案。其中许多已经过时并且针对的是旧版本的Entity Framework。
I've seen many posts and answers regarding how to mark a field as the identity column. Many of them are outdated and are targeting older versions of Entity Framework.
一些资源告诉我在字段上使用属性:
Some resources tell me to use an attribute on the field:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
其他资源告诉我将此代码添加到 OnModelCreating
方法:
Other resources tell me to add this code to OnModelCreating
method:
modelBuilder.Entity<User>().Property(u => u.ID).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
我应该使用哪个?首先,第二,两者都无所谓,还是其他?
Which one should I use? First, second, both, doesn't matter, or something else?
推荐答案
只要主键属性的类型是数字或GUID,按照约定,Code First将自动将密钥配置为标识列。
As long as the type of the primary key property is numeric or GUID, Code First will, by convention, automatically configure the key as an identity column.
这意味着您无需进行任何配置放入您的代码以将属性显式设置为标识列,因为Code First已经为此使用了covention。您设置的数据注释属性或流畅的API配置无用。
That means you don't need to have any of the configuration you put in your code to explicity set the property as an identity column because Code First already use covention for that. The data annotation attribute or fluent API configurations you set are useless.
仅当要禁用身份时,才在数字或GUID类型的主键上使用这些配置。
You use those configurations on numeric or GUID type primary key only if you want to disable the identity.
这篇关于如何使用Entity Framework 6.1正确标记标识列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!