【问题标题】:Can I define a self adjusting Sequence column with Postgres?我可以用 Postgres 定义一个自调整序列列吗?
【发布时间】:2022-01-09 12:10:57
【问题描述】:

我正在运行带有 Postgres 数据库的 EF Core 5,并定义了一些与此类似的实体:

namespace App.Framework.Entities
{
    public class Parent : EntityBase
    {
        [Required]
        public string Name { get; set; } = null!;
    }

    public class Child : EntityBase
    {
        [Required]
        public string Name { get; set; } = null!;
    }

    public class ParentChild : EntityBase
    {
        public Guid ParentId { get; set; }

        public Parent Parent { get; set; } = null!;

        public Guid ChildId { get; set; }

        public Child Child { get; set; } = null!;

        [DefaultValue(0)]
        public decimal Sequence { get; set; }
    }
}

从前端,用户可以创建任意数量的父实体或子实体。对于每个 Parent,用户可以分配多个 Child 实体,从而创建 ParentChild 记录。

我很难达到的目标是添加新的 ParentChild 记录,其序列为 1。共享 ParentId 的任何现有 ParentChild 实体都应将其序列增加 1 以适应这一点。

操作顺序大致如下:

  • 创建 ParentA 和 ChildA
  • 将 ChildA 分配给 ParentA - ParentAChildA 使用序列 1 创建
  • 将 ChildB 分配给 ParentA - ParentAChildA 序列变为 2,ParentAChildB 使用序列 1 创建

内置的 Postgres 序列有什么办法允许这种行为吗?

如果没有,有没有比在创建 ParentChild 时手动编码逻辑更好的解决方案?

【问题讨论】:

    标签: postgresql entity-framework .net-core


    【解决方案1】:

    假设您有一个父表,一个单独的子表,您可以使用序列。

    然后做这样的事情:

    Create table parent (
     parent_id INT GENERATED ALWAYS AS IDENTITY  ,
     name text
    ) ;
    
    create table child (
    parent_id INT, 
    child_id INT GENERATED ALWAYS AS IDENTITY, 
    CONSTRAINT fk_parent
      FOREIGN KEY(parent_id) 
      REFERENCES parent(parent_id)
    );
    

    这样,在提供 parent_id 的子表中插入将自动对子 ID 进行排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 2022-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      相关资源
      最近更新 更多