Violation of PRIMARY KEY constraint

前端 未结 2 1511
迷失自我
迷失自我 2020-12-18 17:09

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 m

2条回答
  •  无人及你
    2020-12-18 18:03

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

提交回复
热议问题