如何使用 Entity Framework Core 配置标识列? [英] How to configure an Identity column using Entity Framework Core?

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

问题描述

如何在 Entity Framework Core 中创建自动递增标识列?

How do I create an Auto increment identity column in Entity Framework Core?

显然,我可以使用 EF6 的 fluent API 来实现.

Obviously I can do it using fluent API for EF6 for example.

推荐答案

由于 EF7 文档很少,我们知道的大部分内容必须从源代码或单元测试中收集.根据EF7源代码中的以下两个单元测试...

Since there is very little EF7 documentation, much of what we know we have to glean from the source or unit tests. According to the following two unit tests in the EF7 source...

这里这里

您可以像这样为 Identity 配置一个属性:

You would configure a property for Identity like this:

b.Property(e => e.Id).ForSqlServer().UseIdentity();

你会像这样为序列配置一个属性:

And you would configure a property for Sequences like this:

ForSqlServer().UseSequence();

由于 aspnet-core 重组,urls 发生了变化,自从第一次询问以来,方法也发生了变化.

The urls have changed due to the aspnet-core reorg, and the methods have also changed since this was first asked.

这里这里

if (_useSequence) 
{
    b.Property(e => e.Identifier).ForSqlServerUseSequenceHiLo();
} 
else 
{
    b.Property(e => e.Identifier).UseSqlServerIdentityColumn();
}

这些网址可能会再次更改(这就是我包含相关代码的原因),但是只需查看网址并转到网站并找出新网址是非常容易的.

It's possible these urls might change again (which is why I include the relevant code), but it's ridiculously easy to just look at the url and go to the site and figure out what the new url is.

真的,我的回答的全部意义在于,您可以通过查看 GitHub 上源代码中的单元测试来自己解决这些问题.你不应该需要有人用勺子把它喂给你.

Really, the whole point of my answer is that you can figure this stuff out yourself just by going and looking at the unit tests in the source code on GitHub. You shouldn't need someone to spoon feed it to you.

更新了 2.1 版的链接(仍然适用于 1.1 和 2.0)

Updated links to version 2.1 (still works for 1.1 and 2.0 as well)

这篇关于如何使用 Entity Framework Core 配置标识列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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