Windows Application Error: Attaching an entity of type Entities failed because another entity of the same type already has the same primary key value

shoaibshafiqahmed
 
on Aug 17, 2021 04:51 AM
352 Views

Hi,

please help to correct code when update a record it shows error.

code and error image attached.

https://drive.google.com/file/d/1rUe06yMihYMn59PGdmu2_a8we1dFY10-/view

Tbl_PartialPayments p = new Tbl_PartialPayments();
p.SerialID = Convert.ToInt32(txtSerialID.Text);
p.CustomerID = Convert.ToInt32(DDLCustName.SelectedValue);
p.EventHeaderID = Convert.ToInt32(MCCBEvent.SelectedValue);
p.EntryDate = txtEntryDate.Value;
p.TotalAmount = Convert.ToInt32(txtTotalAmt.Text);
p.PaidAmount = Convert.ToInt32(txtPaidAmt.Text);
p.Remarks = txtRemarks.Text;
p.LastUpdateBy = Login.GetLoginID;
p.LastUpdateDate = DateTime.Now;
 
db.Entry(p).State = EntityState.Modified;
db.SaveChanges();
Clear();
MessageBox.Show("Record Updated Successfully...", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 17, 2021 04:57 AM

As per your code you are adding new record not updating.

Before update the record set the model value from database and update its data.

Refer below link.

https://forums.asp.net/t/2171053.aspx?Attaching+an+entity+of+type+Entities+failed+because+another+entity+of+the+same+type+already+has+the+same+primary+key+value