C# 更新时违反主键约束错误

C# 更新时违反主键约束错误,c#,sql-server,C#,Sql Server,我有以下代码: using (var connection = new SqlConnection(connetionString)) { try { connection.Open(); } catch(Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("DatabasConnection Done");

我有以下代码:

using (var connection = new SqlConnection(connetionString))
{
    try
    {
        connection.Open();
    }
    catch(Exception e)       
    {
        Console.WriteLine(e.Message);
    }

    Console.WriteLine("DatabasConnection Done");

    DateTime datum = DateTime.Now;
    string LastChangedBy = "System";

    foreach (Person p in myPersons)
    {
        SqlCommand command1 = new SqlCommand();

        try
        {
            command1 = Avreg(p.UnregistrationReason, p.GivenNameNumber, p.ProtectedIdentity, p.CitizenshipDate, connection);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.WriteLine("LALALALA Done");

        command1.Parameters.AddWithValue("@PersonalIdentityNumber", string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
        command1.Parameters.AddWithValue("@FirstName", p.FirstName ?? DBNull.Value.ToString());
        //command1.Parameters.AddWithValue("@LastName", p.LastName ?? DBNull.Value.ToString());
        //command1.Parameters.AddWithValue("@NationalRegistrationCountyCode", p.NationalRegistrationCountyCode ?? DBNull.Value.ToString());
        //command1.Parameters.AddWithValue("@NationalRegistrationMunicipalityCode", p.NationalRegistrationMunicipalityCode ?? DBNull.Value.ToString());
        //command1.Parameters.AddWithValue("@NationalRegistrationDistributionAddress1", p.NationalRegistrationDistributionAddress1 ?? DBNull.Value.ToString());
        //command1.Parameters.AddWithValue("@NationalRegistrationDistributionAddress2", p.NationalRegistrationDistributionAddress2 ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@NationalRegistrationPostCode", p.NationalRegistrationPostCode ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@NationalRegistrationCity", p.NationalRegistrationCity ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@BirthCountyCode", p.BirthCountyCode ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@UnregistrationDate", p.UnregistrationDate ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@BirthParish", p.BirthParish ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@CitizenshipCode", p.CitizenshipCode ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@CitizenshipDate", p.CitizenshipDate ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@NationalRegistrationDate", p.NationalRegistrationDate ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@ForeignDistrubtionAddress1", p.ForeignDistrubtionAddress1 ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@ForeignDistrubtionAddress2", p.ForeignDistrubtionAddress2 ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@ForeignDistrubtionAddress3", p.ForeignDistrubtionAddress3 ?? DBNull.Value.ToString());
         //command1.Parameters.AddWithValue("@ForeignBirthCity", p.ForeignBirthCity ?? DBNull.Value.ToString());

         //command1.Parameters.AddWithValue("@LastChangedBy", LastChangedBy);
         //command1.Parameters.AddWithValue("@LastChangedDate", datum);

         command1.ExecuteNonQuery();

         Console.WriteLine(string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
     }
        }

            Console.WriteLine("Done");
            Console.WriteLine("Alla fält uppdaterade");

        Console.ReadKey();

             }// Put a break-point here, then mouse-over PersonalIdentityNumber...  deserializedList contains everything if you need it
            catch (Exception e)
            {

                Console.Write(" ---- FEL VID INLÄSNINGEN ------  " + e.Message);
                Console.ReadKey();
            }

        }






        public static SqlCommand Avreg(string s, string t, string p, string c, SqlConnection connection)
        {
            try
            {


            var query = "UPDATE Seamen SET FirstName = @FirstName";//, "+
                //"LastName = @LastName, "+
                //"NationalRegistrationCountyCode = @NationalRegistrationCountyCode, "+
                //"NationalRegistrationMunicipalityCode = @NationalRegistrationMunicipalityCode, "+
                //"NationalRegistrationDistributionAddress1 = @NationalRegistrationDistributionAddress1, "+
                //"NationalRegistrationDistributionAddress2 = @NationalRegistrationDistributionAddress2, "+
                //"UnregistrationDate = @UnregistrationDate, "+
                //"NationalRegistrationPostCode = @NationalRegistrationPostCode, "+
                //"NationalRegistrationCity = @NationalRegistrationCity, "+
                //"BirthCountyCode = @BirthCountyCode, "+
                //"BirthParish = @BirthParish, "+
                //"CitizenshipCode = @CitizenshipCode, "+
                //"CitizenshipDate = @CitizenshipDate, " +
                //"NationalRegistrationDate = @NationalRegistrationDate, "+
                //"ForeignDistrubtionAddress1 = @ForeignDistrubtionAddress1, "+
                //"ForeignDistrubtionAddress2 = @ForeignDistrubtionAddress2, "+
                //"ForeignDistrubtionAddress3 = @ForeignDistrubtionAddress3, "+
                //"ForeignBirthCity = @ForeignBirthCity, "+
                //"LastChangedBy = @LastChangedBy, "+
                //"LastChangedDate = @LastChangedDate";

            SqlCommand command1;



            if (c == "0")
            {
                query += ", CitizenshipDate = null";
                command1 = new SqlCommand(query, connection);




            }
            else
            {
                query += ", CitizenshipDate = @CitizenshipDate";
                command1 = new SqlCommand(query, connection);

                command1.Parameters.AddWithValue("@CitizenshipDate", c ?? DBNull.Value.ToString());

            }


            if (p == "J")
            {

                query = "UPDATE Seamen SET FirstName ='Skyddad personuppgift'";//, " +
                //"LastName = 'Se hjälptext', " +
                //"ProtectedIdentity = '1', " +
                //"NationalRegistrationCountyCode = NULL, " +
                //"NationalRegistrationMunicipalityCode = NULL, " +
                //"NationalRegistrationCoAddress = NULL, " +
                ////"NationalRegistrationDistributionAddress1 = NULL, " +
                ////"NationalRegistrationDistributionAddress2 = NULL, " +
                //"UnregistrationDate = NULL, " +
                //"NationalRegistrationPostCode = NULL, " +
                //"NationalRegistrationCity = NULL, " +
                //"BirthCountyCode = NULL, " +
                //"BirthParish = NULL, " +
                //"CitizenshipCode = NULL, " +
                //    //"CitizenshipDate = @CitizenshipDate, " +
                //"NationalRegistrationDate = NULL, " +
                //"ForeignDistrubtionAddress1 = NULL, " +
                //"ForeignDistrubtionAddress2 = NULL, " +
                //"ForeignDistrubtionAddress3 = NULL, " +
                //"UnregistrationReason = NULL, " +
                //"ForeignBirthCity = NULL, " +
                //"LastChangedBy = @LastChangedBy, " +
                //"GivenNameNumber = NULL, " +
                //"LastChangedDate = @LastChangedDate WHERE PersonalIdentityNumber = @PersonalIdentityNumber";



                command1 = new SqlCommand(query, connection);
                command1.Parameters.Clear();
                return command1;
            }

             if ((!string.IsNullOrEmpty(s)) && !string.IsNullOrEmpty(t))
            {
                query += ", UnregistrationReason = @UnregistrationReason";
                query += ", GivenNameNumber = @GivenNameNumber ";

                command1 = new SqlCommand(query, connection);

                command1.Parameters.AddWithValue("@UnregistrationReason", s ?? DBNull.Value.ToString());
                command1.Parameters.AddWithValue("@GivenNameNumber", t ?? DBNull.Value.ToString());

            }
            else if (!string.IsNullOrEmpty(s) && string.IsNullOrEmpty(t))
            {
                query += ", UnregistrationReason = @UnregistrationReason, GivenNameNumber = @GivenNameNumber WHERE PersonalIdentityNumber = @PersonalIdentityNumber";
                command1 = new SqlCommand(query, connection);

                t = "00";
                command1.Parameters.AddWithValue("@UnregistrationReason", s ?? DBNull.Value.ToString());
                command1.Parameters.AddWithValue("@GivenNameNumber", t ?? DBNull.Value.ToString());

            }

            else if (string.IsNullOrEmpty(s) && !string.IsNullOrEmpty(t))
            {
                query += ", GivenNameNumber = @GivenNameNumber WHERE PersonalIdentityNumber = @PersonalIdentityNumber";
                command1 = new SqlCommand(query, connection);

                command1.Parameters.AddWithValue("@GivenNameNumber", t ?? DBNull.Value.ToString());

            }
            else
            {

                    query += ", GivenNameNumber = @GivenNameNumber WHERE PersonalIdentityNumber = @PersonalIdentityNumber";
                    t = "00";
                    command1 = new SqlCommand(query, connection);

                    command1.Parameters.AddWithValue("@GivenNameNumber", t ?? DBNull.Value.ToString());

                    return command1;

            }
             return command1;

        }


        catch(Exception e)
    {
        throw;
    }
}
//}
错误发生在以下位置:

command1.Parameters.AddWithValue("@PersonalIdentityNumber", string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
command1.Parameters.AddWithValue("@FirstName", p.FirstName ?? DBNull.Value.ToString());
//command1.Parameters.AddWithValue("@LastName", p.LastName ?? DBNull.Value.ToString());

command1.ExecuteNonQuery();

Console.WriteLine(string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
我得到一个错误:

违反主键约束“PK_logSeamen”。无法插入 对象“dbo.logSeamen”中存在重复密钥。声明已被修改 终止

是否需要清除
SqlCommand

看来我有这个扳机

USE [Bums]
GO
/****** Object:  Trigger [dbo].[trSeamen_LogI]    Script Date: 05/16/2016 11:43:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[trSeamen_LogI] ON [dbo].[Seamen] AFTER INSERT AS
INSERT INTO [logSeamen] ([PersonalIdentityNumber], [ProtectedIdentity], [ReferedCivicRegistrationNumber], [UnregistrationReason], [UnregistrationDate], [MessageComputerComputer], [GivenNameNumber], [FirstName], [MiddleName], [LastName], [NotifyName], [NationalRegistrationDate], [NationalRegistrationCountyCode], [NationalRegistrationMunicipalityCode], [NationalRegistrationCoAddress], [NationalRegistrationDistributionAddress1], [NationalRegistrationDistributionAddress2], [NationalRegistrationPostCode], [NationalRegistrationCity], [NationalRegistrationNotifyDistributionAddress], [NationalRegistrationNotifyPostCode], [NationalRegistrationNotifyCity], [ForeignDistrubtionAddress1], [ForeignDistrubtionAddress2], [ForeignDistrubtionAddress3], [ForeignDistrubtionCountry], [ForeignDate], [BirthCountyCode], [BirthParish], [ForeignBirthCity], [CitizenshipCode], [CitizenshipDate], [Email], [Telephone], [Mobiletelephone], [Gender], [NotNewsPaper], [Note], [StatusCode], [NationalRegistrationCode], [RegistrationDate], [LastUpdatedFromNavet], [TemporaryDistrubtionAddress1], [TemporaryDistrubtionAddress2], [TemporaryDistrubtionAddress3], [TemporaryDistrubtionCountry], [Password], [VisibilityLevel],[SeamanIdentity], [LastChangedBy], [LastChangedDate], LogAction)
SELECT [PersonalIdentityNumber], [ProtectedIdentity], [ReferedCivicRegistrationNumber], [UnregistrationReason], [UnregistrationDate], [MessageComputerComputer], [GivenNameNumber], [FirstName], [MiddleName], [LastName], [NotifyName], [NationalRegistrationDate], [NationalRegistrationCountyCode], [NationalRegistrationMunicipalityCode], [NationalRegistrationCoAddress], [NationalRegistrationDistributionAddress1], [NationalRegistrationDistributionAddress2], [NationalRegistrationPostCode], [NationalRegistrationCity], [NationalRegistrationNotifyDistributionAddress], [NationalRegistrationNotifyPostCode], [NationalRegistrationNotifyCity], [ForeignDistrubtionAddress1], [ForeignDistrubtionAddress2], [ForeignDistrubtionAddress3], [ForeignDistrubtionCountry], [ForeignDate], [BirthCountyCode], [BirthParish], [ForeignBirthCity], [CitizenshipCode], [CitizenshipDate], [Email], [Telephone], [Mobiletelephone], [Gender], [NotNewsPaper], [Note], [StatusCode], [NationalRegistrationCode], [RegistrationDate], [LastUpdatedFromNavet], [TemporaryDistrubtionAddress1], [TemporaryDistrubtionAddress2], [TemporaryDistrubtionAddress3], [TemporaryDistrubtionCountry], [Password], [VisibilityLevel], [SeamanIdentity], [LastChangedBy], [LastChangedDate], 'INSERT' FROM INSERTED
如何确保它不违反主键约束

更新2

USE [Bums]
GO
/****** Object:  Trigger [dbo].[trSeamen_LogU]    Script Date: 05/16/2016 12:53:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[trSeamen_LogU] ON [dbo].[Seamen] AFTER UPDATE AS
INSERT INTO [logSeamen] ([PersonalIdentityNumber], [ProtectedIdentity], [ReferedCivicRegistrationNumber], [UnregistrationReason], [UnregistrationDate], [MessageComputerComputer], [GivenNameNumber], [FirstName], [MiddleName], [LastName], [NotifyName], [NationalRegistrationDate], [NationalRegistrationCountyCode], [NationalRegistrationMunicipalityCode], [NationalRegistrationCoAddress], [NationalRegistrationDistributionAddress1], [NationalRegistrationDistributionAddress2], [NationalRegistrationPostCode], [NationalRegistrationCity], [NationalRegistrationNotifyDistributionAddress], [NationalRegistrationNotifyPostCode], [NationalRegistrationNotifyCity], [ForeignDistrubtionAddress1], [ForeignDistrubtionAddress2], [ForeignDistrubtionAddress3], [ForeignDistrubtionCountry], [ForeignDate], [BirthCountyCode], [BirthParish], [ForeignBirthCity], [CitizenshipCode], [CitizenshipDate], [Email], [Telephone], [Mobiletelephone], [Gender], [NotNewsPaper], [Note], [StatusCode], [NationalRegistrationCode], [RegistrationDate], [LastUpdatedFromNavet], [TemporaryDistrubtionAddress1], [TemporaryDistrubtionAddress2], [TemporaryDistrubtionAddress3], [TemporaryDistrubtionCountry], [Password], [VisibilityLevel], [SeamanIdentity],[LastChangedBy], [LastChangedDate], LogAction)
SELECT [PersonalIdentityNumber], [ProtectedIdentity], [ReferedCivicRegistrationNumber], [UnregistrationReason], [UnregistrationDate], [MessageComputerComputer], [GivenNameNumber], [FirstName], [MiddleName], [LastName], [NotifyName], [NationalRegistrationDate], [NationalRegistrationCountyCode], [NationalRegistrationMunicipalityCode], [NationalRegistrationCoAddress], [NationalRegistrationDistributionAddress1], [NationalRegistrationDistributionAddress2], [NationalRegistrationPostCode], [NationalRegistrationCity], [NationalRegistrationNotifyDistributionAddress], [NationalRegistrationNotifyPostCode], [NationalRegistrationNotifyCity], [ForeignDistrubtionAddress1], [ForeignDistrubtionAddress2], [ForeignDistrubtionAddress3], [ForeignDistrubtionCountry], [ForeignDate], [BirthCountyCode], [BirthParish], [ForeignBirthCity], [CitizenshipCode], [CitizenshipDate], [Email], [Telephone], [Mobiletelephone], [Gender], [NotNewsPaper], [Note], [StatusCode], [NationalRegistrationCode], [RegistrationDate], [LastUpdatedFromNavet], [TemporaryDistrubtionAddress1], [TemporaryDistrubtionAddress2], [TemporaryDistrubtionAddress3], [TemporaryDistrubtionCountry], [Password], [VisibilityLevel], [SeamanIdentity],[LastChangedBy], [LastChangedDate], 'UPDATE' FROM INSERTED
关于:

违反主键约束“PK_logSeamen”。无法插入 对象“dbo.logSeamen”中存在重复密钥。声明已被修改 终止

看起来您在Seamen表上有一个更新触发器。检查触发器正在执行的操作,必要时进行修复。

RE:

违反主键约束“PK_logSeamen”。无法插入 对象“dbo.logSeamen”中存在重复密钥。声明已被修改 终止


看起来您在Seamen表上有一个更新触发器。检查触发器正在执行的操作,并在必要时进行修复。

触发器正在从插入的表中插入一系列值,您说PersonalIdentityNumber是LogSeamen中的主键。很明显,每次更新都会违反它,因为它在第一次插入操作时就已经插入了。删除PK_LogSeamen,或者为PK创建另一个自动生成的列

您的触发器从插入的表中插入一系列值,您说PersonalIdentityNumber是LogSeamen中的主键。很明显,每次更新都会违反它,因为它在第一次插入操作时就已经插入了。删除PK_LogSeamen,或者为PK创建另一个自动生成的列

更新可以在一个表上发生多次。您的
logSeamen
表用于跟踪更改,并且总是可能正在更新的行在过去某个时候已经更新过。您不能将
PersonalIdentityNumber
(或
Seamen
表中的任何列)标记为
logSeamen
表中的主键

为了解决这个问题

logSeamen
表中的
PersonalIdentityNumber
列中删除主键约束,以便可以多次插入相同的
PersonalIdentityNumber


(可选)添加一个新列(例如
logSeamenId
)作为主键,并具有
标识(1,1)
,这将自动为该行生成一个数字。

表上的更新可能会发生多次。您的
logSeamen
表用于跟踪更改,并且总是可能正在更新的行在过去某个时候已经更新过。您不能将
PersonalIdentityNumber
(或
Seamen
表中的任何列)标记为
logSeamen
表中的主键

为了解决这个问题

logSeamen
表中的
PersonalIdentityNumber
列中删除主键约束,以便可以多次插入相同的
PersonalIdentityNumber



(可选)添加一个新列(例如
logSeamenId
)作为主键,该列具有
INDENTITY(1,1)
,将自动为该行生成一个数字。

您的personalidentitynumber不是自动递增的吗?@BugFinder否不是。然而。代码在不包含特定的PersonalIdentityNumber的情况下工作,这似乎很奇怪。您也有一个bug,当连接失败时,它将崩溃并继续执行代码的其余部分。错误表示您正在尝试插入,而此帖子的标题为Update。看起来您正在执行插入而不是更新。因此,看起来您有一个带有主键的表,并且您正在尝试插入一个重复键。您需要使用Update命令(不是Insert)。请编辑您的问题以仅包含相关代码。请阅读如何创建。您的personalidentitynumber不是自动递增吗?@BugFinder不是。然而。代码在不包含特定的PersonalIdentityNumber的情况下工作,这似乎很奇怪。您也有一个bug,当连接失败时,它将崩溃并继续执行代码的其余部分。错误表示您正在尝试插入,而此帖子的标题为Update。看起来您正在执行插入而不是更新。因此,看起来您有一个带有主键的表,并且您正在尝试插入一个重复键。您需要使用Update命令(不是Insert)。请编辑您的问题以仅包含相关代码。请阅读如何创建一个。你有一个只用于插入或更新的触发器吗?你有一个只用于插入或更新的触发器吗?你是对的,我一开始也是这么想的。然而,LogSeamen的目的是记录每行发生的更改(更新)。因此,可以多次插入相同的PersonalIdentityNumber。如果我在LogSeamen上搜索特定的PersonalIdentityNumber,我会得到多个具有相同PersonalIdentityNumber的行,因为正如我所说,它会记录发生的更改,因此可以在LogSeamen中多次插入相同的PersonalIdentityNumber。我修复了它。问题是,有时候,没有什么需要更新的,所以它假设它是完全相同的。我包括了一个“LastChanged”列,以允许它始终更新到当前时间,因此现在无论发生什么,它都将始终更新。谢谢你的帮助。你说得对,一开始我也是这么想的。然而,LogSeamen的目的是记录每行发生的更改(更新)。因此,可以多次插入相同的PersonalIdentityNumber。如果我在LogSeamen上搜索特定的PersonalIdentityNumber,我会得到多个具有相同PersonalIdentityNumber的行,因为正如我所说,它会记录发生的更改,因此可以在LogSeamen中多次插入相同的PersonalIdentityNumber。我修复了它。问题是有些人