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

Upvotes: 1

Views: 5240

Answers (2)

Joel C
Joel C

Reputation: 5567

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

Upvotes: 4

cdhowie
cdhowie

Reputation: 168958

You need to obtain the existing object and update its uri property and then call clientDB.SubmitChanges(). The code you have right now quite explicitly asks it to insert a new record.

Presumably something like this would work:

using (clientsDBDataContext clientDB = new clientsDBDataContext()) {
    var client = clientDB.clientURIs.Where(c => c.clientID == clientID).Single();
    client.uri = uri.ToString();
    clientDB.SubmitChanges();
}

Upvotes: 3

Related Questions