1
Answer

How to solve violation of primary key cannot insert duplicate

Photo of Garima Bansal

Garima Bansal

1y
504
1

I am trying to insert value from code in which i want talukcode = regioncode like 

model.talukcode = model.regioncode;

previously it was like

 model.villagecode = MaxValue + 1;

but now i am trying

model.talukcode = model.regioncode;

and i am getting an error 

System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_ppatalukmaster'. Cannot insert duplicate key in object 'dbo.ppatalukmaster'. The duplicate key value is (3, 3).
The statement has been terminated.

Is there any way to solve this error through code.

Answers (1)

0
Photo of Jayraj Chhaya
309 6k 94.2k 1y

The error message indicates that the primary key constraint on the ppatalukmaster table is being violated. This means that the combination of values being inserted into the primary key columns already exists in the table. In this case, the duplicate key value is (3, 3).

To solve this error, you need to ensure that the combination of values being inserted into the primary key columns is unique. One way to achieve this is by checking if the combination already exists in the table before performing the insert operation.

// Check if the combination of values already exists in the table
bool combinationExists = CheckCombinationExists(model.talukcode, model.regioncode);

if (!combinationExists)
{
    // Perform the insert operation
    InsertData(model);
}
else
{
    // Handle the duplicate key error
    Console.WriteLine("Error: Duplicate key value");
}

In the above code, the CheckCombinationExists method checks if the combination of talukcode and regioncode already exists in the table. If it does not exist, the InsertData method is called to perform the insert operation. Otherwise, an appropriate error message or handling logic can be implemented.

By implementing this check, you can prevent the violation of the primary key constraint and avoid inserting duplicate values into the table.

Accepted