Simultaneous insertion of items and sales with C #, Windows Forms and PostgreSQL

0

Hello, I'm developing a sales screen in C # Windows Forms. I'm just in the beginning of the project, but I came across a situation where I'm not sure what to do. I am using a PostgreSQL database, I created a table called SALE and another ITEMSEND. The logic I am using is as follows: When inserting the first product it creates a row in the SALES table generating a code that is of type SERIAL. This code is then stored and used to insert the items from that sale into the ITENDS table. That's where the problem comes from, when there is more than one machine inserting at the same time, it may be a problem to insert items with COD from the wrong sale, if I happen to record several sales at the same time, just because I need to recover the code from my sale that I am doing on my machine. What is the best way for me to solve this problem? What do you do to not end up throwing items in on sales other than mine?

    
asked by anonymous 12.07.2018 / 00:46

1 answer

0

You need to open a transaction, in the first insert it returns the code that was inserted and then uses it to insert the items.

If all goes well, execute the Commit, otherwise RollBack.

Example:

using (NpgsqlConnection conexao = new NpgsqlConnection())
{
    conexao.Open();
    using (NpgsqlTransaction transacao = conexao.BeginTransaction())
    {
        try
        {
            string codigoVenda;
            using (NpgsqlCommand cmdInser = new NpgsqlCommand("Insert into [tabela]... returning id", conexao, transacao))
            {
                using (NpgsqlDataReader dr = cmdInser.ExecuteReader())
                {
                    dr.Read();
                    codigoVenda = dr[0].ToString();
                }

            }


            List<string> itens = new List<string>(); //apensa simulando uma lista de itens

            foreach (string item in itens)
            {
                //item.VendaId = codigoVenda; //Atribui o código da venda no item

                using (NpgsqlCommand cmdItem = new NpgsqlCommand("Insert into [tabela]...", conexao, transacao))
                {
                    cmdItem.ExecuteScalar();
                }

            }


            //ocorreu tudo certo
            transacao.Commit();
        }
        catch
        {
            //deu erro
            transacao.Rollback();
        }
    }
}
    
12.07.2018 / 00:58