1

I have a table in my database that is in dire need of an auto-incrementing field. To create one, I ran these following SQL statements towards the aforementioned database:

CREATE SEQUENCE table_id_seq
    INCREMENT 1
    NO MINVALUE
    NO MAXVALUE
    START 1
    CACHE 1;

ALTER TABLE ONLY table ALTER COLUMN id SET DEFAULT nextval('table_id_seq'::regclass);
ALTER TABLE ONLY table
    ADD CONSTRAINT table_id PRIMARY KEY (id);

However, when I try to INSERT any two values into table I still get a primary key violation error. I don't understand what I'm missing to make it auto-incrementing.

4

2 回答 2

0

使用实体框架并对数据库进行更改时,您必须记住从数据库更新模型。此外,您必须在再次测试代码之前保存模型,否则它将使用旧模型,而不会得到您想要的结果。

于 2013-07-07T12:13:33.473 回答
0

序列创建完成后,我们可以调用 NEXTVAL('table_id_seq') 自动生成一个新值。

1.将序列链接到唯一列

ALTER TABLE ONLY 
ALTER COLUMN id 
SET DEFAULT NEXTVAL('table_id_seq');
ALTER TABLE ONLY table
    ADD CONSTRAINT table_id PRIMARY KEY (id);
于 2013-07-07T12:47:07.720 回答