PRIMARY KEY约束违反 [英] Violation of PRIMARY KEY constraint

查看:535
本文介绍了PRIMARY KEY约束违反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录的唯一标识,所以我不能让我的ID

I am trying to record unique identifiers, so I cannot afford to have a duplicate record of my ID's

我收到看起来像这样的,当我尝试错误的重复记录PRIMARY KEY约束来更新我的SQL Server表名为客户

I am getting an error that looks like this when I try to update my SQL Server table called Clients.

违反 PK_clients。 。无法插入对象db_owner.clients'
重复键

Violation of PRIMARY KEY constraint 'PK_clients'. Cannot insert duplicate key in object 'db_owner.clients'.

此代码看起来像这样:

public void Subscribe(string clientID, Uri uri)
{
    clientsDBDataContext clientDB = new clientsDBDataContext();
    var client = new ServiceFairy.clientURI();
    client.clientID = clientID;
    client.uri = uri.ToString();
    clientDB.clientURIs.InsertOnSubmit(client);
    clientDB.SubmitChanges();
}            



任何想法我怎么能去修复这一点,所以我可以更新我行所有我希望能够做的是,当行存在那么只更新相关联的URI,如果它不存在提交新的clientID的URI +

Any Idea how I can go about fixing this, so I can update my rows, all I want to be able to do is when a row exists then only update the associated URI, and if it doesn't exist to submit a new clientID + URI,

感谢

约翰

推荐答案

您想要做的是第一检查现有的记录,如果它不存在,然后的添加一个新的。您的代码将始终尝试添加一个新的记录。我假设你使用LINQ2SQL(基于 InsertOnSubmit )?

What you want to do is first check for the existing record, and if it doesn't exist, then add a new one. Your code will always attempt to add a new record. I'm assuming you're using Linq2Sql (based on the InsertOnSubmit)?

public void Subscribe(string clientID, Uri uri)
{
    using(clientsDBDataContext clientDB = new clientsDBDataContext())
    {
        var existingClient = (from c in clientDB.clientURIs
                              where c.clientID == clientID
                              select c).SingleOrDefault();

        if(existingClient == null)
        {
            // This is a new record that needs to be added
            var client = new ServiceFairy.clientURI();
            client.clientID = clientID;
            client.uri = uri.ToString();
            clientDB.clientURIs.InsertOnSubmit(client);
        }
        else
        {
            // This is an existing record that needs to be updated
            existingClient.uri = uri.ToString();
        }
        clientDB.SubmitChanges();
    }
}

这篇关于PRIMARY KEY约束违反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆