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

时间:2016-10-31 12:06:50

标签: postgresql asp.net-core entity-framework-core

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

我有以下代码:

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

当我更新数据库时(进行迁移后),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

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

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

 protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.UseSerialColumns();

    }

您应该在 DbContextClass 中使用它来为主键创建自动递增的值

答案 2 :(得分:0)

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

要将身份列用于新模型上所有值生成的属性,只需将以下内容放在上下文的OnModelCreating()中:

builder.ForNpgsqlUseIdentityColumns();

这将创建使所有具有.ValueGeneratedOnAdd()的键和其他属性在默认情况下具有标识。您可以使用ForNpgsqlUseIdentityAlwaysColumns()始终拥有身份,也可以使用UseNpgsqlIdentityColumn()和UseNpgsqlIdentityAlwaysColumn()逐个属性地指定身份。

postgres efcore value generation