C# 用户窗体保存事务在数据库表中重复两次

问题描述 投票:0回答:1

我创建的应用程序运行完美,但我偶尔会遇到一个随机问题。此问题不会持续发生,而是偶尔发生。

在其中一次保存操作中,相同的操作在数据库表中重复两次,有时会导致输入重复的数据。

正如我提到的,奇怪的是这个问题时不时地随机发生。

这是我用来将数据保存到数据库表的代码:

private async void btnSave_Click(object sender, EventArgs e)
{
    await ExecuteSaveOperationAsync();
}

private async Task ExecuteSaveOperationAsync()
{
    if (comBoxLocation.Text == "-- Select Location --")
    {
        MessageBox.Show("Please select a location first");
        return;
    }

    if (!dateTimePicker.Checked)
    {
        MessageBox.Show("Select date first");
        return;
    }

    using (var db = new TTApplicationEntities())
    {
        using (var transaction = db.Database.BeginTransaction())
        {
            try
            {
                var selectedDate = dateTimePicker.Value;
                var costCenterFromComboBox = (int)comBoxLocation.SelectedValue;

                var costCenterDetails = await db.tblCostCenters
                    .SingleOrDefaultAsync(cc => cc.CostCenterId == costCenterFromComboBox);

                if (costCenterDetails == null)
                {
                    MessageBox.Show("Cost Center not found");
                    return;
                }

                var businessUnitDetails = await db.tblBusinessUnits
                    .SingleOrDefaultAsync(bu => bu.BusinessUnitId == costCenterDetails.BusinessUnitId);

                if (businessUnitDetails == null)
                {
                    MessageBox.Show("Business Unit not found");
                    return;
                }

                var vatFromDB = await db.tblVATs.FirstOrDefaultAsync();
                var vatProducts = (vatFromDB?.VATPercentage ?? 0) * 0.01m + 1;

                var productsListWithoutVAT = new List<tblJournal>();
                var productsListVAT = new List<tblJournal>();
                var fullTotalProducts = 0m;

                var productsWithoutVAT = new List<tblJournal>();
                var productsVAT = new List<tblJournal>();

                foreach (DataGridViewRow row in dataGridViewSales.Rows)
                {
                    if (row.IsNewRow) continue;

                    var categoryCode = Convert.ToInt32(row.Cells[8].Value);
                    var categoryDetails = await db.tblCategories
                        .SingleOrDefaultAsync(cd => cd.CategoryCode == categoryCode);

                    if (categoryDetails != null)
                    {
                        var amount = Convert.ToDecimal(row.Cells[5].Value);
                        productsWithoutVAT.AddRange(new[]
                        {
                            CreateJournalEntry(TRANS_DATE:selectedDate ,ACCOUNT_TYPE:"Ledger" , ACCOUNT_CODE:"4100101", UNIT_CODE:businessUnitDetails.BusinessUnitCode.ToString(), COST_CENTER_CODE: costCenterDetails.CostCenterCode.ToString(), CATEGORY_CODE:categoryDetails.CategoryCode.ToString(),BANK_DEPOSIT_VOUCHER:0 ,AMOUNT_CUR_DEBIT:0,AMOUNT_CUR_CREDIT:Math.Round(amount / vatProducts, 4, MidpointRounding.AwayFromZero),  DESCRIPTION: $"{costCenterDetails.LocationCode} {categoryDetails.ProductSalesDescription}" , CURRENCY_RATE: 1 , TAXGROUP:"Local-CardVAT" , TAXITEMGROUP:categoryDetails.CategoryTaxItemGroup , TRANSACTION_REPORT:categoryDetails.CategoryName , TRANSACTION_TYPE:"Sales"),
                        });

                        productsVAT.AddRange(new[]
                        {
                            CreateJournalEntry(TRANS_DATE:selectedDate ,ACCOUNT_TYPE:"Ledger" , ACCOUNT_CODE:"2115100", UNIT_CODE:businessUnitDetails.BusinessUnitCode.ToString(), COST_CENTER_CODE: costCenterDetails.CostCenterCode.ToString(),BANK_DEPOSIT_VOUCHER:0 ,AMOUNT_CUR_DEBIT:0,AMOUNT_CUR_CREDIT: Math.Round(amount - amount / vatProducts, 4, MidpointRounding.AwayFromZero) , DESCRIPTION: $"{costCenterDetails.LocationCode} {categoryDetails.ProductVatDescription}" , CURRENCY_RATE: 1 , TAXCODE:"PVAT-LSCard" , TRANSACTION_REPORT:categoryDetails.CategoryName, TRANSACTION_TYPE: "Sales"),
                        });

                        fullTotalProducts += amount;
                    }
                }

                //Journal Cash in Safe 
                var productsCashinSafeCostCenter = CreateJournalEntry(TRANS_DATE: selectedDate, ACCOUNT_TYPE: "Bank", ACCOUNT_CODE: "C_" + costCenterDetails.CostCenterName, UNIT_CODE: businessUnitDetails.BusinessUnitCode.ToString(), COST_CENTER_CODE: costCenterDetails.CostCenterCode.ToString(), TYPE_CODE: "11", BANK_DEPOSIT_VOUCHER: 0, AMOUNT_CUR_DEBIT: fullTotalProducts, AMOUNT_CUR_CREDIT: 0, DESCRIPTION: $"{costCenterDetails.LocationCode} Cash in Safe", CURRENCY_RATE: 1, TRANSACTION_TYPE: "Total Sales");

                //Journal Payment Option
                var paymentOption = await CreatePaymentJournalEntries(db, dataGridViewPayment.Rows, costCenterDetails, businessUnitDetails, selectedDate, vatProducts);

                Decimal cashMoeny = 0;

                foreach (DataGridViewRow row in dataGridViewPayment.Rows)
                {
                    if (row.Cells[0].Value != null && row.Cells[1].Value.ToString() == "Cash")
                    {
                        cashMoeny = Convert.ToDecimal(row.Cells[2].Value);
                    }
                }

                if (cashMoeny > 0)
                {
                    var costCenterCashMoney = CreateCostCenterCashMoneyEntry(CostCenterID: costCenterDetails.CostCenterId, CashMoeny: cashMoeny, Date: selectedDate);
                    db.tblCostCentersCashMoneys.Add(costCenterCashMoney);
                }

                db.tblJournals.AddRange(productsWithoutVAT);
                db.tblJournals.AddRange(productsVAT);
                db.tblJournals.Add(productsCashinSafeCostCenter);
                db.tblJournals.AddRange(paymentOption);

                await db.SaveChangesAsync();
                transaction.Commit();

                this.Close();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

我使用以下代码来防止用户同时运行程序的多个实例:

internal static class Program
{
    private static Mutex mutex;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool isNewInstance;
        string appName = "MyUniqueApplicationName";

        // Create a new mutex with a unique name.
        mutex = new Mutex(true, appName, out isNewInstance);

        if (!isNewInstance)
        {
            // If an instance is already running, show an error message and exit.
            MessageBox.Show("The application is already running.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }


        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new frmLogin());

        // Release the mutex when the application exits.
        GC.KeepAlive(mutex);
    }
}

我用过

var transaction = db.Database.BeginTransaction()

试图解决这个问题,但没有帮助。

c# database userform
1个回答
0
投票

可能是网络问题。有时可能会发生您必须处理代码库中的网络部分。

© www.soinside.com 2019 - 2024. All rights reserved.