c# - 使用 Entity Framework Core 在部分主键上自动递增

标签 c# asp.net entity-framework postgresql entity-framework-core

我已经使用 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 提供程序有关。

来自 EF Core documentation :

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/

相关文章:

c# - 显示隐藏的 WPF 窗口

c# - 谁可以访问 MVVM 模式中的数据库

c# - 使用 javascript(客户端验证)更改 ASP.NET 自定义验证器的错误消息?

c# - 可以生成 Excel 报告并将其推送到客户端计算机,而无需将文件保存在服务器中

javascript - 如何在asp.net中渲染html

c# - 实体子项上 where 条件的 Linq 表达式

c# - 如何从 Asp Net Core WebApi 将日志存储到 Azure 表存储?

c# - Web API2 NinjectWebCommon.cs 没有出现

c# - Entity Framework TPT 继承子类型

asp.net-mvc - 使用 IRepository 进行 Entity Framework 测试 - 延迟加载问题