How to mark identity column properly with 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 正确标记标识列?
基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30