使用 Entity Framework Core 在部分主键上自动递增 [英] Auto-increment on partial primary key with Entity Framework Core

查看:33
本文介绍了使用 Entity Framework Core 在部分主键上自动递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 EF Core fluent API 声明了以下模型:

I have declared the following model using the EF Core fluent API:

modelBuilder.Entity<Foo>()
    .HasKey(p => new { p.Name, p.Id });

当我在 PostgreSQL 中创建数据库时,两个字段都被标记为主键,但 Id 字段未标记为自动增量.我也尝试添加

Both fields are marked as the primary key when I create the database in PostgreSQL but the Id field is not marked as auto increment. I have also tried to add

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

到 Foo 下的 Id 字段,而不会对迁移代码产生任何影响.虽然是PPK,但有没有办法制作Id AI?

to the Id field under Foo without it making any difference on the migration code. Is there a way to make the Id AI although it is a PPK?

推荐答案

好吧,那些数据注解应该可以解决问题,也许与 PostgreSQL Provider 有关.

Well those Data Annotations should do the trick, maybe is something related with the PostgreSQL Provider.

来自 EF Core 文档:

根据所使用的数据库提供程序,可能会生成值客户端通过 EF 或在数据库中.如果该值是由数据库,那么 EF 可能会在您添加实体时分配一个临时值到上下文.这个临时值将被替换为SaveChanges 期间数据库生成的值.

Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during SaveChanges.

您也可以尝试使用此 Fluent Api 配置:

You could also try with this Fluent Api configuration:

modelBuilder.Entity<Foo>()
            .Property(f => f.Id)
            .ValueGeneratedOnAdd();

但正如我之前所说,我认为这与数据库提供程序有关.尝试向您的数据库添加一个新行,稍后检查是否为 Id 列生成了一个值.

But as I said earlier, I think this is something related with the DB provider. Try to add a new row to your DB and check later if was generated a value to the Id column.

这篇关于使用 Entity Framework Core 在部分主键上自动递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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