public async Task <IActionResult> SyncProductsInventory() { var errorList = new List <string>(); try { if (_db.Connection.State == System.Data.ConnectionState.Closed) { await _db.Connection.OpenAsync(); } var query = new ProductQueries(_db); var products = await query.GetAllProductInventories(); foreach (var product in products) { var found = _context.ProductInventory.FirstOrDefault(p => p.LocationId == int.Parse(product.warehouse_id.ToString()) && p.ProductId == int.Parse(product.product_id.ToString())); if (found == null) { var productExists = await _context.Product.FindAsync(int.Parse(product.product_id.ToString())); if (productExists != null) { var newProduct = new ProductInventory { ProductId = int.Parse(product.product_id.ToString()), Balance = string.IsNullOrEmpty(product.stock) ? 0 : decimal.Parse(product.stock), BinCode = "", LocationId = int.Parse(product.warehouse_id.ToString()), ModifiedDate = DateTime.Now, }; await _context.ProductInventory.AddAsync(newProduct); await _context.SaveChangesAsync(); } } else { found.Balance = string.IsNullOrEmpty(product.stock) ? 0 : decimal.Parse(product.stock); await _context.SaveChangesAsync(); } } _db.Connection.Close(); } catch (Exception ex) { errorList.Add("order taxes:" + ex.ToString()); } await _emailSender.SendEmailAsync("*****@*****.**", "Sync Finished: Products Inventory", $"Sync Finished: Products Inventory. {string.Join(",", errorList)}"); return(Ok(errorList)); }