0

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

System.Data.Entity.Infrastructure.DbUpdateException: '更新条目时出错。有关详细信息,请参阅内部异常。SqlException:违反主键约束“PK_ad_gb_rsm”。无法在对象“dbo.ad_gb_rsm”中插入重复键。重复键值为 (100001)。该语句已终止。

下面是我正在使用的 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;
        }
    }
}

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

4

1 回答 1

0

内部异常说明了一切:

SqlException:违反主键约束“PK_ad_gb_rsm”。无法在对象“dbo.ad_gb_rsm”中插入重复键。重复键值为 (100001)

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

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

DBS.ad_gb_rsm.Add(acc);

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

如果此更改跟踪概念对您来说是新概念,请阅读此 MDSN 文章

于 2021-06-11T11:11:59.593 回答