使用 EntityFramework Core 时自动递增的值在 PostgreSQL 中不起作用

Wou*_*ter 5 postgresql entity-framework-core asp.net-core

似乎 PostgreSQL 的自动增量功能似乎不起作用。

我有以下代码:

namespace project.Models
{
   public class DatabaseModel
   {
       [Key]
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
       [Column(Order=1, TypeName="integer")]
       public int ID { get; set; }
   }
 }
Run Code Online (Sandbox Code Playgroud)

当我更新数据库时(在执行迁移后),ID 列是主键而不是自动增量。

当我尝试向数据库添加新对象时,出现以下错误:

Microsoft.EntityFrameworkCore.DbContext[1]
  An exception occurred in the database while saving changes.
  Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Npgsql.PostgresException: 23502: null value in column "ID" violates not-null constraint
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助解决这个问题吗?如何让密钥自动递增?

小智 9

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
Run Code Online (Sandbox Code Playgroud)

要用于新模型上的identity columns所有值生成属性,只需将以下内容放入您的DBContext事件OnModelCreating()处理程序中:

protected override void OnModelCreating(ModelBuilder builder) 
{
    builder.ForNpgsqlUseIdentityColumns();
}
Run Code Online (Sandbox Code Playgroud)

这将确保默认ValueGeneratedOnAdd()使用的所有密钥和其他属性。Identity

您可以使用ForNpgsqlUseIdentityAlwaysColumns()has always,也可以使用和Identity逐个属性指定身份。UseNpgsqlIdentityColumn()UseNpgsqlIdentityAlwaysColumn()

Postgres efcore 价值生成


Phi*_*ill 5

因为您创建了具有特定类型的列,所以integer您需要serial为 PostgreSQL指定类型来为您生成 id。

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL