我已经使用 EF Core fluent API 声明了以下模型:
modelBuilder.Entity<Foo>()
.HasKey(p => new { p.Name, p.Id });
当我在 PostgreSQL 中创建数据库时,两个字段都被标记为主键,但 Id 字段未被标记为自动递增。我也尝试添加
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
到 Foo 下的 Id 字段,而不会对迁移代码产生任何影响。 Id AI虽然是PPK,但有没有办法制作?
最佳答案
那些数据注释应该可以解决问题,也许与 PostgreSQL 提供程序有关。
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 配置:
modelBuilder.Entity<Foo>()
.Property(f => f.Id)
.ValueGeneratedOnAdd();
但正如我之前所说,我认为这与数据库提供程序有关。尝试向您的数据库添加一个新行,稍后检查是否为 Id
列生成了一个值。
关于c# - 使用 Entity Framework Core 在部分主键上自动递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36155429/