【发布时间】: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