locked
Entity Framework:- Violation of PRIMARY KEY constraint . Cannot insert duplicate key RRS feed

  • Question

  • User-639631676 posted

    Hello

    I am inserting new data in a few different tables with the same data from my main table, but after inserting say 4 or 5 records I get the above error for one of the tables, here is my code

    public static void InsertSnookerMainTable(string FirstName, string LastName, string Team)
    {
    try
    {
    using (var DB = new FinalWringtonValeDB())
    {

    Table1 SnookerMainTable = new Table1();
    SnookerMainTable.FirstName = FirstName;
    SnookerMainTable.LastName = LastName;


    Table2 Div1Breaks = new Table2();
    Div1Breaks.FirstName = FirstName;
    Div1Breaks.LastName = LastName;

    Table3 Div2Breaks = new Table3();
    Div2Breaks.FirstName = FirstName;
    Div2Breaks.LastName = LastName;

    Table4 Contact = new Table4();
    Contact.FirstName = FirstName;
    Contact.LastName = LastName;

    DB.SnookerHandicaps.Add(SnookerMainTable);
    DB.Div1Breaks.Add(Div1Breaks);
    DB.Div2Breaks.Add(Div2Breaks);
    DB.Contacts.Add(Contact);
    DB.SaveChanges();
    }
    }
    catch (Exception ex)
    {
    Error:- ** Violation of PRIMARY KEY constraint . Cannot insert duplicate key **
    return;
    }
    }

    Friday, April 21, 2017 8:49 PM

Answers

  • User-639631676 posted

    I have since found the issue it was in another bit of code, but thanks for all your help

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 24, 2017 12:39 PM

All replies

  • User-1509636757 posted

    I suggest to debug and Identify which of the table insertion code is throwing this error and check in database, if any of the field for which you are inserting data is defined as Primary Key and being received duplicate values. I suggest to keep an Id or RecordId kind of field with int/bigint datatype with Identity Seed (1,1) as Primary key to avoid such errors.

    Sunday, April 23, 2017 1:22 PM
  • User-271186128 posted

    Hi SnookerTable,

    Entity Framework:- Violation of PRIMARY KEY constraint . Cannot insert duplicate key

    According to your error message, I think the reason is that the PK of data which you are inserting is already existed in database.
    You could debug to check the Message in Exception ex. It will tell you which is duplicate.
    For example:

    Before insert new records into database, you could check whether it is duplicate.

    Best regards,
    Dillion

    Monday, April 24, 2017 9:13 AM
  • User-639631676 posted

    I have since found the issue it was in another bit of code, but thanks for all your help

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 24, 2017 12:39 PM