DbUpdateException 同时使用 LINQ to Database 更新记录

DbUpdateException Whiles updating record using LINQ to Database

我一直在尝试以 window 形式更新数据库中的记录,但每次单击更新按钮时都会出现此错误。

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.

下面是我使用的 LINQ 代码

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;
        }
    }
}

我不知道我做错了什么。我是新手。

内部异常说明一切:

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)

您的代码试图执行 INSERT 操作,但失败了,因为它违反了主键的唯一约束。

问题的根本原因是以下行:

DBS.ad_gb_rsm.Add(acc);

因为 Add 调用您的 acc 实体的 state 变成 Added 而不是 Modified。如果您删除 Add 方法调用,那么它将将该实体视为 Modified 并将执行 UPDATE 操作。

如果您不熟悉此更改跟踪概念,请阅读 this MDSN article