Click here to Skip to main content
15,920,053 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
im triying use foreach in a dataset to update a sql server, if the element alredy exist just catch the error and try with the next. My table have 13 elements and this foreach is giving the error of the first element 13 times :

System.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint ;PK_share1;. Cannot insert duplicate key in object ;dbo.share1&. The duplicate key value is (4008).

if (changes != null)
                    {
                        foreach (DataTable table in changes.Tables)
                        {
                            foreach (DataRow dr in table.Rows)
                            {
                                try
                                {
                                    adapter.Update(changes);
                                    
                                }

                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.ToString());
                                   
                                }

                              
                            }
                        }
                    }
Posted
Updated 25-May-15 1:03am
v2

You are not really do an in-loop update here, but rather call Update on your DataAdapter for each row in each table...
The problem is that DataAdapter.Update - internally - runs over all the rows that have a status of inserted, updated or deleted...
Please read here: https://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1[^]
 
Share this answer
 
my solution for do exactly what i want:

SQL
adapter.ContinueUpdateOnError = true;
                  adapter.Update(changes);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900