I have been trying to update a record in the database in window form but each time I click the update button I get this error.
System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.' SqlException: Violation of PRIMARY KEY constraint 'PK_ad_gb_rsm'. Cannot insert duplicate key in object 'dbo.ad_gb_rsm'. The duplicate key value is (100001). The statement has been terminated.
Below is the LINQ code I am using
private void btu_Update_Click(object sender, EventArgs e)
{
if (radioButtonMale.Checked)
{
gender = "male";
}
else if (radioButtonFemale.Checked)
{
gender = "female";
}
userID = Convert.ToDecimal(txtUserID.Text);
//ad_gb_rsm acc = DBS.ad_gb_rsm.First(s => s.ICube_id.Equals(userID));
var query = (from upd in DBS.ad_gb_rsm where upd.ICube_id == userID select upd).ToList();
foreach (var acc in query)
{
acc.user_type = comboBoxUser_Type.Text;
acc.JDate = dateTimeCrtDate.Text;
acc.title = comboBoxTitle.Text;
acc.fName = txtFname.Text;
acc.mName = txtMName.Text;
acc.lName = txtLName.Text;
acc.DOB = dateTimeDOB.Value.ToString();
acc.Gender = gender;
acc.Phone = txtPhoneNumber.Text;
acc.zip_code = txtZipCode.Text;
acc.POB = txtPOBAddress.Text;
acc.address = txtAddress.Text;
acc.email = txtEmail.Text;
acc.City = txtCity.Text;
acc.State = txtState.Text;
acc.marrital_Status = comboBoxMS.Text;
acc.NOK_Name = txtNKName.Text;
acc.NOK_Phone = txtNKNumber.Text;
acc.NOK_Address = txtNOKAddress.Text;
acc.NOKRela = txtNOKRela.Text;
acc.create_dt = dateTimeCrtDate.Value.ToString();
Image img = LogUserImage.Image;
if (img.RawFormat != null)
{
if (ms != null)
{
img.Save(ms, img.RawFormat);
acc.Picture = ms.ToArray();
}
}
acc.Dept_Sector = comboBoxDeptSector.Text;
acc.Position = comboBoxPosition.Text;
acc.JDate = dateTimeJoinDt.Value.ToString();
acc.Empl_Status = comboBoxUserStatus.Text;
acc.username = txtUsername.Text;
acc.password = txtPassword.Text;
acc.incu_copany_name = txtIncu_CompanyName.Text;
acc.createdBy = AdministratorBankLogin.AdminUserLogin.Username;
try
{
DBS.ad_gb_rsm.Add(acc);
DBS.SaveChanges();
MessageBox.Show("User Created Successfully");
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
}
I do not know what I am doing wrong. I am new to this.
The inner exception says everything:
SqlException: Violation of PRIMARY KEY constraint 'PK_ad_gb_rsm'. Cannot insert duplicate key in object 'dbo.ad_gb_rsm'. The duplicate key value is (100001)
Your code tried to perform an INSERT
operation, but failed because it violates the unique constraint of the primary key.
The root cause of your problem is the following line:
DBS.ad_gb_rsm.Add(acc);
Because of the Add
call your acc
entity's state become Added
rather than Modified
. If you delete that Add
method call then it will treat that entity as Modified
and will perform an UPDATE
operation.
If this change tracking concept is new to you then please read this MDSN article.