Return Value ID C # NpgsqlCommand

1

After inserting a line of information into a given table, I need to retrieve the ID value to fill my object, my code looks like this:

using (NpgsqlConnection pgsqlConnection = new NpgsqlConnection(conn)
        {           
            pgsqlConnection.Open();
            String sql = "INSERT INTO public.localpo(NOME) VALUES (:nome)";
            using (NpgsqlCommand pgsqlcommand = new NpgsqlCommand(sql, pgsqlConnection))
            {
    pgsqlcommand.Parameters.Add(new NpgsqlParameter("nome", "Ricardo Soares"));
            pgsqlcommand.ExecuteNonQuery();
            }
        }

With this code I can insert information into the database without problems, getting the doubt, and to retrieve the id that was generated?

below the sql code used to generate the table:

CREATE TABLE public.localpo (
id bigint NOT NULL DEFAULT nextval('localpo_id_seq'::regclass),
nome character varying(255) COLLATE pg_catalog."default",
CONSTRAINT pk_id_localpo PRIMARY KEY (id)
)
    
asked by anonymous 06.09.2018 / 23:38

2 answers

0

There is a command called returning that serves just to return one of the fields, example based on its string:

INSERT INTO public.localpo(NOME) VALUES ('exemplo') returning id;
    
07.09.2018 / 01:07
1

That?

using (var conn = new NpgsqlConnection(conn) {           
    conn.Open();
    using (var cmd = new NpgsqlCommand("INSERT INTO public.localpo(NOME) VALUES (:nome)", conn)) {
        cmd.Parameters.Add(new NpgsqlParameter("nome", "Ricardo Soares"));
        var IdInserido = (int)cmd.ExecuteScalar();
    }
}
    
06.09.2018 / 23:45