违反主键约束'PK_EMPLOYEE'。无法在对象

时间:2019-02-05 11:30:05

标签: c# ado.net sql-server-2014-express

我正在尝试更新记录,但显示“违反主键约束,无法在对象/表中插入重复的键”。 这个错误听起来像是在我更新记录时调用了“ ADD EMPLOYEE块”。

如果我放弃主键,它将插入另一条记录(已更新)而不是更新前一条! 注意:已经阅读了许多问题可以解决它!

static public void UpdateEmployee(Employee employee)
{
    String conString = ConfigurationManager.ConnectionStrings["EMPLOYES"].ConnectionString;

    SqlConnection conn = new SqlConnection(conString);
    using (conn)
    {
        SqlCommand cmd = new SqlCommand("UpdateEmployeeRecord", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@EmployeeID", SqlDbType.NVarChar, 8).Value = employee.EmployeeID;
        cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = employee.FirstName;
        cmd.Parameters.Add("@LastNmae", SqlDbType.NVarChar, 50).Value =     employee.LastName;
        cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = employee.Email;
        cmd.Parameters.Add("@Telephone", SqlDbType.NVarChar, 50).Value = employee.Telephone;

        conn.Open();
        cmd.ExecuteNonQuery();
    }
}

static public void AddEmployee(Employee employee)
{
    String conString = ConfigurationManager.ConnectionStrings["EMPLOYES"].ConnectionString;

    SqlConnection conn = new SqlConnection(conString);
    using (conn)
    {
        SqlCommand cmd = new SqlCommand("AddNewEmployee", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@EmployeeID", SqlDbType.NVarChar, 8).Value = employee.EmployeeID;
        cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = employee.FirstName;
        cmd.Parameters.Add("@LastNmae", SqlDbType.NVarChar, 50).Value = employee.LastName;
        cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = employee.Email;
        cmd.Parameters.Add("@Telephone", SqlDbType.NVarChar, 50).Value = employee.Telephone;

        conn.Open();
        cmd.ExecuteNonQuery(); //(X) Exception is here
        }
    }

使用的程序

ALTER PROCEDURE [dbo].[UpdateEmployeeRecord]
(
    @EmployeeID NVARCHAR(8),@FirstName  NVARCHAR(50),
@LastNmae NVARCHAR(50),@Email NVARCHAR(50),
@Telephone Nvarchar(50)
)
AS
BEGIN
    UPDATE [DBO].[EMPLOYEE] SET  FirstName = @FirstName,
            LastName = @LastNmae, Email = @Email, Telephone = @Telephone
        WHERE EmployeeID = @EmployeeID 
    END 

我希望记录会被更新,但这违反了主键约束。

1 个答案:

答案 0 :(得分:0)

在过程@LastNmae中使用的错误是@LastName,但没有影响