违反 PRIMARY KEY 约束

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

问题描述

我正在尝试记录唯一标识符,因此我无法承受我的 ID 的重复记录

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

当我尝试更新名为 Clients 的 SQL Server 表时,出现类似这样的错误.

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

违反 PRIMARY KEY 约束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,如果它不存在则提交一个新的客户端 ID + 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 约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)