Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi everybody i'm using linq to insert data into two tables have relation one to many
when insert second time this message appear ??

SQL
Violation of PRIMARY KEY constraint 'PK__customer__26A1118D08EA5793'. Cannot insert duplicate key in object 'dbo.customeraddress'.
The statement has been terminated.




my code :

C#
DbDataContext db = new DbDataContext();

            customer cust = new customer();
            
            cust.firstname = textBox1.Text;
            cust.Lastname = textBox2.Text;
        
            db.customers.InsertOnSubmit(cust);
            db.SubmitChanges();

            customeraddress custaddress = new customeraddress();
           
                custaddress.states = textBox3.Text;
                custaddress.address1 = textBox4.Text;

                cust.customeraddresses.Add(custaddress);
            db.SubmitChanges();
Posted
Updated 12-Sep-15 11:22am
v2
Comments
jgakenhe 12-Sep-15 19:42pm    
You probably have a unique index on one of the columns in that table. Depending on how your database is set up, you should probably drop it.
sreeyush sudhakaran 13-Sep-15 0:20am    
1)Unique Key you are trying to insert may exists in the table already or
2)Unique Key may be foreign key from another table which may not yet present in the parent table.

If you are trying to insert foreign keys give importance in insertion sequence
Parent table should be filled before child tables referencing that.

1 solution

The error message is quite clear, you're trying to insert a row that contains the exact same data that already exists in another row in your table in the column(s) you have defined as primary key.

The purpose of the primary key is to prevent duplicates, hence the error message.

In order to see the primary key, open Sql Server Management Studio, navigate to your database and table, right click the table and select Design. There you should see a key icon in front of the column(s) that is primary key.

Another option is to run a query to get the primary key info. For that you can try the following:
SQL
SELECT a.TABLE_CATALOG,
       a.TABLE_NAME,
       a.COLUMN_NAME,
       a.ORDINAL_POSITION
FROM  INFORMATION_SCHEMA.KEY_COLUMN_USAGE a
WHERE a.CONSTRAINT_NAME = 'PK__customer__26A1118D08EA5793'
ORDER BY a.ORDINAL_POSITION
 
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