[英]How to configure an Identity column using Entity Framework Core?
How do I create an Auto increment identity column in Entity Framework Core?如何在 Entity Framework Core 中创建自动增量标识列?
Obviously I can do it using fluent API for EF6 for example.显然,例如,我可以使用 EF6 的 fluent API 来做到这一点。
In latest version of EF7 there is a new extension method to set identity column在最新版本的 EF7 中有一个新的扩展方法来设置标识列
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>(b =>
{
b.HasKey(e => e.Identifier);
b.Property(e => e.Identifier).ValueGeneratedOnAdd();
});
}
Since there is very little EF7 documentation, much of what we know we have to glean from the source or unit tests.由于 EF7 文档很少,我们知道的大部分内容必须从源代码或单元测试中收集。 According to the following two unit tests in the EF7 source...
根据EF7源代码中的以下两个单元测试...
You would configure a property for Identity like this:您将为 Identity 配置一个属性,如下所示:
b.Property(e => e.Id).ForSqlServer().UseIdentity();
And you would configure a property for Sequences like this:您可以为 Sequences 配置一个属性,如下所示:
ForSqlServer().UseSequence();
The urls have changed due to the aspnet-core reorg, and the methods have also changed since this was first asked.由于 aspnet-core 重组,url 已更改,自首次询问以来,方法也已更改。
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.这些 url 可能会再次更改(这就是我包含相关代码的原因),但是只需查看 url 并转到站点并找出新 url 是非常容易的。
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.真的,我的回答的重点是,您可以通过查看 GitHub 上源代码中的单元测试来自己解决这些问题。 You shouldn't need someone to spoon feed it to you.
你不应该需要有人用勺子把它喂给你。
EDIT: Updated links to version 2.1 (still works for 1.1 and 2.0 as well)编辑:更新了 2.1 版的链接(仍然适用于 1.1 和 2.0)
With latest bits EF Core 1.0 and up you should use使用最新的 EF Core 1.0 及更高版本,您应该使用
builder.Entity<ApplicationUser>().Property<int>(nameof(ApplicationUser.AccountNo))
.UseSqlServerIdentityColumn()
看起来他们再次改变了它,现在的新方法是:
.UseIdentityColumn()
Here is how to do it explicitly in the event that you want to OR it's not the default behaviour.这是在您想要或它不是默认行为的情况下明确执行的方法。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>(b =>
{
b.Key(e => e.Identifier);
b.Property(e => e.Identifier).ForSqlServer().UseIdentity();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.