使用Entity Framework Core在部分主键上自动递增 [英] Auto-increment on partial primary key with 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字段,而对迁移代码没有任何影响。
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?
推荐答案
那些数据注释应该可以解决问题,也许有办法使Id AI成为PPK吗?与PostgreSQL提供程序有关。
Well those Data Annotations should do the trick, maybe is something related with the PostgreSQL Provider.
来自 EF核心文档:
根据所使用的数据库提供程序,可能会通过
客户端生成值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屋!