Die Transaktion zum Speichern des C#-Benutzerformulars wird in der Datenbanktabelle zweimal wiederholtC#

Ein Treffpunkt für C#-Programmierer
Guest
 Die Transaktion zum Speichern des C#-Benutzerformulars wird in der Datenbanktabelle zweimal wiederholt

Post by Guest »

Die von mir erstellte Anwendung funktioniert einwandfrei, aber ich stoße gelegentlich auf ein zufälliges Problem. Dieses Problem tritt nicht regelmäßig, sondern sporadisch auf.
Bei einem der Speichervorgänge wird dieselbe Aktion zweimal in der Datenbanktabelle wiederholt, was manchmal dazu führt, dass doppelte Daten eingegeben werden.< /p>
Wie ich bereits erwähnt habe, ist das Seltsame, dass dieses Problem von Zeit zu Zeit zufällig auftritt.
Hier ist der Code, den ich zum Speichern von Daten verwendet habe Datenbanktabelle:

Code: Select all

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();
var productsListVAT = new List();
var fullTotalProducts = 0m;

var productsWithoutVAT = new List();
var productsVAT = new List();

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);
}
}
}
}
Ich verwende den folgenden Code, um zu verhindern, dass der Benutzer mehrere Instanzen des Programms gleichzeitig ausführt:

Code: Select all

internal static class Program
{
private static Mutex mutex;

/// 
/// The main entry point for the application.
/// 
[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);
}
}
Ich habe
verwendet

Code: Select all

var transaction = db.Database.BeginTransaction()
Ich habe versucht, dieses Problem zu beheben, aber es hat nicht geholfen.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post