简体   繁体   中英

Npgsql.PostgresException: '55000: currval of sequence “student_folio_id_seq” is not yet defined in this session'

I am new in C# syntax and trying out Insert data into two different table when user hit the Insert button. At the same time, 2nd Insert statement need to grab the 1st Insert statement id as it's foreign key. Primary key id is auto increment.

This sql works in PHP but seems not in C# and I get this throw error message Npgsql.PostgresException: '55000: currval of sequence "student_folio_id_seq" is not yet defined in this session'.

Can any expert in C# Postgres db give me advice where goes wrong in syntax? And good if can specify with examples.

Here is my code:

 connection.Open();
 NpgsqlCommand cmd = new NpgsqlCommand();
 cmd.Connection = connection;

 cmd.CommandText = "INSERT INTO student_folio 
 (f_name,l_name,ic,dob,gender,remark)VALUES(@f_name, 
 @l_name,@ic,@dob,@gender,@remark) RETURNING id";

 cmd.CommandText = "INSERT INTO contact (s_id, address)VALUES((SELECT 
 currval(pg_get_serial_sequence('student_folio', 'id'))),@address) ";
 cmd.CommandType = CommandType.Text;

seems you are trying to re assign your cmd.CommandText with new dml value. Try this.

connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;

cmd.CommandText = "INSERT INTO student_folio (f_name,l_name,ic,dob,gender,remark)VALUES(@f_name, @l_name,@ic,@dob,@gender,@remark) RETURNING id; " +
            "INSERT INTO contact (s_id, address)VALUES((SELECT currval(pg_get_serial_sequence('student_folio', 'id'))),@address);";     
cmd.CommandType = CommandType.Text;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM