gpt4 book ai didi

c# - 使用 Entity Framework (C#) 覆盖 PostgreSql 中的序列

转载 作者:行者123 更新时间:2023-11-29 13:54:19 24 4
gpt4 key购买 nike

在 PostgreSQL 数据库上使用 Entity Framework 添加记录时,如何覆盖 ID 字段中的序列/序列?

添加记录时,序列/序列自动递增 ID 工作正常,但我需要编写一个迁移脚本,我迁移的旧记录必须保留其旧 ID。

如果我直接向服务器发送一个 INSERT 查询,它工作正常,但是当使用 Entity Framework 时,它们只是从 1、2、3 等开始。

最佳答案

您应该在使用自动生成的值进行任何插入之前重置数据库中的序列。它高度依赖于表 DDL。最常用的 ID 自动生成有两个示例:

/*
-- Be careful with these 3 lines if you already have such objects in the your DB
drop table if exists t1;
drop table if exists t2;
drop sequence if exists seq_t2_id;
*/

-- Using serial type for ID
create table t1 (t1_id serial, t1_name char varying);
insert into t1 (t1_id, t1_name) values (22, 'aaa');
select setval(pg_get_serial_sequence('t1', 't1_id'), (select max(t1_id) from t1)); -- Reset serial value
insert into t1 (t1_name) values ('bbb');
select * from t1;

-- Using sequence to generate IDs
create sequence seq_t2_id;
create table t2(t2_id bigint default nextval('seq_t2_id'), t2_name char varying);
insert into t2(t2_id, t2_name) values (22, 'aaa');
select setval('seq_t2_id', (select max(t2_id) from t2)); -- Update sequence
insert into t2 (t2_name) values ('bbb');
select * from t2;

关于c# - 使用 Entity Framework (C#) 覆盖 PostgreSql 中的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35120544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com