I need to update a right record with ExternalID = Id of inserted record. And I try to check this field (ExternalID) in SOQL, but get an error System.QueryException: List has no rows for assignment to SObject. What is wrong here?

global static void upd() {
    RestRequest req = RestContext.request;
    String thisID = req.params.get('Id');
    Product__c product = [SELECT Id FROM Product__c WHERE ExternalID__c =: thisID];
    Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(req.requestbody.tostring());
    for(String fieldName : params.keySet()) {
        product.put(fieldName, params.get(fieldName));
    update product;

Test (coverage 100%, but error):

static void testupd() {
    Product__c test = new Product__c(Name__c = 'Orange');
    insert test;
    RestRequest req = new RestRequest();
    req.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() +
                     + test.Id;
    //even this can't help to put id of inserted test-product into ExternalID__c:
    req.params.put('ExternalID__c', test.Id);
    req.httpMethod = 'PATCH';
    req.addHeader('Content-Type', 'application/json');
    req.requestBody = Blob.valueOf('{"Name__c": "Cherry"}'); 
    RestContext.request = req;
    //update method:
    //Error is here:
    Product__c updatedRecord = [SELECT Name__c
                                FROM Product__c
                                WHERE ExternalID__c =: test.Id];
    System.assert(updatedRecord.Name__c == 'Cherry');

1 Answer 1

req.params.put('ExternalID__c', test.Id);


String thisID = req.params.get('Id');


Id is not the same as ExternalID__c. They need to match up correctly. Or you should be reading the ID from the URI, since that's how you designed it. You have the Id in two different places, which simply should not be necessary.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .