Violation of PRIMARY KEY constraint

前端 未结 2 1507
迷失自我
迷失自我 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 17:57

    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();
    }
    
    0 讨论(0)
  • 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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题