You should use Sequences to automatically create your primary identifier inside the database when inserting new objects.
For a more detailed answer (code), I need to know the structure of the wsmsmrs210
table.
Generally, if your datatable is created using:
CREATE SEQUENCE sequence_name; CREATE TABLE wsmsmrs210 ( epiphanyKey bigint default nextval('sequence_name'), ... )
then your code should look like this:
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=postgres;Password=password;Database=epiphany;"); conn.Open(); // opens the connection NpgsqlCommand cmd = new NpgsqlCommand("INSERT INTO wsmsmrs210 (transaction,license,dateOfActv,time) VALUES(:a,:b,:c,:d)", conn); ... // add parameters :a, :b, :c, :d via cmd.Parameters.Add(...) here cmd.ExecuteNonQuery(); // Add next two lines if you need last inserted id in code cmd = new NpgsqlCommand("SELECT CURRVAL('sequence_name')", conn); var id = cmd.ExecuteScalar(); conn.Close();
If you want to have maximum reliability, then you should write a saved function in PLPGSQL that will take your field values as input parameters, insert the value into the table, get the last insert identifier and return it.
source share