Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 views
in Technique[技术] by (71.8m points)

c# - Violation of PRIMARY KEY constraint

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

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

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

The code for this looks like so:

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();
}            

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,

Thanks

John

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...