【问题标题】:Auto-Incremented value not working in PostgreSQL when using EntityFramework Core使用 Entity Framework Core 时,自动增量值在 PostgreSQL 中不起作用
【发布时间】:2017-03-13 12:24:28
【问题描述】:

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

谁能帮忙解决这个问题?如何让密钥自动递增?

【问题讨论】:

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


    【解决方案1】:

    由于您创建了具有特定类型integer 的列,您需要将类型指定为serial,以便PostgreSQL 为您生成id。

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

    【讨论】:

    【解决方案2】:
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    

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

    builder.ForNpgsqlUseIdentityColumns();
    

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

    postgres efcore value generation

    【讨论】:

      【解决方案3】:
       protected override void OnModelCreating(ModelBuilder modelBuilder)
          {
              modelBuilder.UseSerialColumns();
      
          }
      

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

      【讨论】:

        猜你喜欢
        • 2020-03-30
        • 2016-07-09
        • 1970-01-01
        • 1970-01-01
        • 2018-06-19
        • 2020-07-28
        • 1970-01-01
        • 2023-03-14
        • 2019-03-12
        相关资源
        最近更新 更多