C#/.NET: Concurrent Execution of Stored Procedures Returns Same Result for Different Orders

I’m encountering an issue in my .NET service where I’m executing stored procedures for invoice creation (InsertFactura) in a foreach loop for multiple orders. Despite distinct entries being created in the database table “comprobantes” with unique invoice numbers, the InsertFactura method returns the same invoice number for different orders.

I’ve attempted to address this by using a lock within the foreach loop to handle concurrency, and I’ve also tried modifying the method implementations to be asynchronous. However, the issue persists.

For context, here’s a simplified version of my code structure:

if (pedidos != null)
                    {
                        _logger.LogInformation(pedidos.Count.ToString() + " pedidos por procesar");
                        int indexPedido = 0;

                        foreach (var item in pedidos)
                        {
                            try
                            {
                                indexPedido++;
                                _logger.LogInformation("Ingresando detalle de pedido " + indexPedido.ToString() + " de " + pedidos.Count.ToString());

                                if (repository.existePedido(item.IdPedido).count > 0)
                                {
                                    _logger.LogInformation("Cambiando estado del pedido existente " + item.IdPedido.ToString());
                                    await apiSdk.setPedidoAsDescargado(item.IdPedido);
                                }
                                else
                                {
                                    _logger.LogInformation("#" + item.IdPedido.ToString() + " Precio: " + item.PrecioFinal.ToString() + " Cuit: " + item.Cuit + " DNI:" + item.Dni);
                                    lock(lockObject)
                                    { 
                                        PedidoImport datosFactura = repository.InsertFactura(item.PrecioFinal, conf.Facturacion.nroVendedor, item.Cuit, item.Dni, conf.Facturacion.puntoDeVenta, item.IdPedido, item.Direccion, item.Nombre, item.Apellido);
                                        _logger.LogInformation("#" + item.IdPedido.ToString() + " Factura insertada: " + datosFactura.nroComprobante.ToString());
                                        foreach (var itemDetalle in item.PedidoDetalles)
                                        {
                                            repository.InsertDetalleFactura(datosFactura.nroComprobante, Convert.ToInt32(itemDetalle.CodigoArticulo), itemDetalle.Descripcion, itemDetalle.Cantidad, itemDetalle.PrecioUnitario, 0, conf.Facturacion.idListaPrecio, conf.Facturacion.deposito);
                                            _logger.LogInformation("Insertando detalle de pedido NroComprobante" + datosFactura.nroComprobante + " CodArticulo:" + itemDetalle.CodigoArticulo + " " + itemDetalle.Descripcion + " CANT:" + itemDetalle.Cantidad.ToString() + "PrecioUnitario:" + itemDetalle.PrecioUnitario.ToString());
                                        }
                                    }
                                    await apiSdk.setPedidoAsDescargado(item.IdPedido);
                                }
                            }
                            catch (Exception ex)
                            {
                                repository.logError("Creación Factura Error", "Error insertando pedido " + item.IdPedido.ToString() + ", Detalles: " + ex.Message + " " + ex.StackTrace);
                                _logger.LogError("Error insertando pedido " + ex.Message + ex.StackTrace);
                            }

                        }
                    }

And here are the relevant implementations of the stored procedure methods:

public PedidoImport InsertFactura(decimal totalComprobante, int vendedor, string cuit, string dni, int puntoVenta, int idPedido, string Direccion, string Nombre, string Apellido)
        {
            NumberFormatInfo nfi = new NumberFormatInfo();
            nfi.NumberDecimalSeparator = ".";

            
            string sqlFTS = string.Empty;
            if (!String.IsNullOrEmpty(cuit))
            {
              sqlFTS= "EXEC  [dbo].[dvr_FACTURA_GENERAL_InsertFromEcommerce] @TotalComprobante =" + totalComprobante.ToString(nfi)+ ", @ven_idesec=" + vendedor + ", @cuit=" + cuit + " , @dni=" + dni + " , @pdv_idesec=" + puntoVenta ;
            }
            else
            {
            sqlFTS = "EXEC  [dbo].[dvr_FACTURA_GENERAL_InsertFromEcommerce] @TotalComprobante =" + totalComprobante.ToString(nfi) + ", @ven_idesec=" + vendedor + ", @dni=" + dni + " , @pdv_idesec=" + puntoVenta ; ;
            }
            var pedido = dataContext.Set<PedidoImport>().FromSqlRaw(sqlFTS.ToString());
            return pedido.ToList().FirstOrDefault();
        }

        public void InsertDetalleFactura(int nroComprobante, int codigoArticulo, string descripcionItem, decimal cantidad, decimal precioUnitario,decimal ajuste,int listaDePrecio, int deposito)
        {
            NumberFormatInfo nfi = new NumberFormatInfo();
            nfi.NumberDecimalSeparator = ".";

            string sqlFTS = string.Empty;

            sqlFTS = "EXEC  [dbo].[dvr_DETALLE_FACTURA_GENERAL_insertFromEcommerce] @com_idesec =" + nroComprobante + ", @art_idesec=" + codigoArticulo + ", @dfg_des='" + descripcionItem.Replace("'","''") + "' , @dfg_can=" + cantidad.ToString(nfi) + " , @dfg_preuni=" + precioUnitario.ToString(nfi) + ",@dfg_aju=" + ajuste.ToString(nfi) + ",@tdp_idesec=" + listaDePrecio + ",@lda_idesec=" + deposito;
            
            var pedido = dataContext.Set<PedidoImport>().FromSqlRaw(sqlFTS.ToString());
            dataContext.Database.ExecuteSqlRaw(sqlFTS);
           
        }

        public PedidoCount existePedido(int idPedido)
        {
            var sqlFTS = "EXEC [dbo].[existePedido] @idPedido = " + idPedido;
            var pedido = dataContext.Set<PedidoCount>().FromSqlRaw(sqlFTS.ToString());

            return pedido.ToList().FirstOrDefault();
        }

I’ve attempted to address this by using a lock within the foreach loop to handle concurrency, and I’ve also tried modifying the method implementations to be asynchronous. However, the issue persists.

I’m looking for guidance on how to ensure that each order receives a unique invoice number without encountering concurrency issues. Any insights or suggestions would be greatly appreciated. Thanks in advance!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật