问题
How do I override the serial/sequence in an ID field when adding records with Entity Framework on a PostgreSQL database?
The serial/sequence auto incrementing ID works fine, when adding records, but I need to write a migration script where the old records I migrate must maintain their old ID's.
It works fine if I just shoot an INSERT query directly to the server, but when doing with with Entity Framework, they just start from 1, 2, 3 etc.
回答1:
You should to reset sequence in the database before any insertions using autogenerated values. It is highly depending on table DDL. There are two example for most used ID's autogen:
/*
-- 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;
来源:https://stackoverflow.com/questions/35120544/override-serial-sequence-in-postgresql-with-entity-framework-c