如何使用 Entity Framework 6.1 正确标记标识列?

How to mark identity column properly with Entity Framework 6.1?(如何使用 Entity Framework 6.1 正确标记标识列?)

本文介绍了如何使用 Entity Framework 6.1 正确标记标识列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多关于如何将字段标记为标识列的帖子和答案.其中许多已经过时并且针对的是旧版本的实体框架.

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.

p>

这意味着您不需要在代码中进行任何配置来明确地将属性设置为标识列,因为 Code First 已经为此使用了约定.您设置的数据注释属性或 fluent 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 正确标记标识列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何使用 Entity Framework 6.1 正确标记标识列?

基础教程推荐