Find your content:

Search form

You are here

Prevent DMLException when lookup's external id is unknown

 
Share

Imagine a Custom SObject X with a lookup field for Custom SObject Y. Y has an external ID field EID. As described in this answer, I can create a record X like this:

Y y = new Y(EID = 1);
X x = new X(Y__r = y);
insert x;

However, this fails if no Y record with EID = 1 exists.

To prevent this failure we could create a set of all external ids:

Set<Decimal> externalIds = new Set<Decimal>();
List<Y> ys = [SELECT EID FROM Y];
for (Y y : ys) {
    externalIds.add(y.EID);
}
X x = new X();
if (externalIds.contains(1)) {
    Y y = new Y(EID = 1);
    x.Y__r = y;
}
insert x;

However, this won't scale. If you have e.g. 500,000 Y records, you could never create this set.

Also, the solution has to scale for thousands of records of X, so directly querying the given EID won't work either.

Is there a way to directly bind X to Y if and only if a record of Y exists that has the given EID?


Attribution to: Jolanda Verhoef

Possible Suggestion/Solution #1

How about SOQL?

You can always ask if there is Object Y with such Id

//eidSet_FromX  - Set Of EId values from X object

 set<String> eidSet_FromY = new Set<String>();

for(Y someY : [SELECT EID FROM Y WHERE EID IN : eidSet_FromX]){
    eidSet_FromY.add(someY.EID);
}

Attribution to: Artur Kępczyński

Possible Suggestion/Solution #2

What about using saveResults to see whats happened? All depends on whether you want to check before insert that the data is valid; in your 'trivial' case looking at EID and whether it exists or not. Or whether you want to try it and see what the results is; this can be useful when validation rules, triggers, etc... may come into play.

An example maybe:-

Y y = new Y(EID = 1);
X x = new X(Y__r = y);

Database.SaveResult[] srList = Database.insert(x,false);
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted x');
    }
    else {
       System.debug('Failed to insert x');
    }

Attribution to: Richard Durrant
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/30876

My Block Status

My Block Content