we have a .NET 3.5 WinForms app that uses Linq2Sql to insert records into SQL Server 2008 database. It worked fine for the past couple of years until yesterday we noticed that a submitchanges() call lead to multiple insertions of the records. Instead of inserting each new record just once (as it always does and should do), the query ran five times in total and so each record ended up being inserted 5 times!!!
This of course is a huge problem, we cannot have duplicate records in our database appearing randomly.
We have no idea why this happenned, I am suspecting some network issue. Does anyone have a clue what could be the reason, how to troubleshoot it and how to get rid of it?
edit: here’s a code sample:
if (selectedOrders > 0)
{
try
{
foreach (Customer cust in selectedOrders.Select(a=>a.Customer))
{
Invoice newInvoice = new Invoice();
newInvoice = cust.CustomerID;
// ... other code here
db.Invoices.InsertOnSubmit(newInvoice);
db.SubmitChanges();
}
}
catch (Exception ex)
{
log.Items.Add("Error: " + ex.Message);
log.SelectedIndex = log.Items.Count - 1;
log.Update();
}
}
Thanks.
Jan
You should use
Distinct()method after selecting customers because, there may be same customer in selected orders. Also when inserting multiple records to one table, it is better to usedb.SubmitChanges()outside theforeachloop.