function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
TsukasaTsukasa 

How do you work with relations

I'm trying to bulk upsert some data, here is the structure

 

Account *parent*
Provider__c "child of Account*

Practice__c *child of Provider__c*

I always have the account id.

 

I need to add a new provider and its practices so I have something as follows.

 

Provider__c prov = new Provider__c;
Practice__c prac = new Practice__c;

prov.Account_Name__c = accountID;
prov.Name= "value";
...etc

prac.Provider__c = prov.ID
...etc

upsert(prov)
upsert(prac)

 
As you can see prov.ID is going to be empty so it flags an error trying to do the upsert.
How to I correctly link these items and upsert them?

Thanks

TsukasaTsukasa

Still looking for an answer to my issue.

JWykelJWykel

Provider__c would need an External Id that is known at time of creation.

Provider__c provider = new Provider__c();
provider.Account_Name__c = accountID;
provider.Name = "value";
provider.SomeExternalId__c = "123";

Practice__c prac = new Practice__c();
prac.Provider__r = new Provider__r(){ SomeExternalId__c = "123" };

upsert new sObject[]{ provider, prac };

 Yes, you could use the Account's ID as the external id of the provider (making a sort of 1-1 relationship).

Things to note:
Do not attempt to set prac.Provider__r to provider.  When setting a reference, the reference instance should *only* have the external id field set, nothing else.

The parent object must come before the child object in the sObject array in the upsert/create.

upsert/create will batch types together and can have a maximum of 6 (I believe) batches. What this means is that you cannot do something like this:

upsert new sObject[]{ prov1, prac1, prov2, prac2, ... prov7, prac7 };

You would need to do something like this:

upsert new sObject[]{ prov1, prov2, ... prov7, prac1, prac2, ... prac7 };

JPClark3JPClark3

You just need to upsert the Providers, before you work on the Pactices

 

Provider__c prov = new Provider__c;
Practice__c prac = new Practice__c;

prov.Account_Name__c = accountID;
prov.Name= "value";
...etc
upsert(prov)


prac.Provider__c = prov.ID
...etc

upsert(prac)

 

JWykelJWykel

My appologies, JPClark3's method is correct.  I was mistaking upsert with update.  Upsert cannot have multiple types in the same call, see here:

http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_upsert.htm

 

You may run into issues with the code he posted, if you are calling from C#, though.  Upsert requires an external id field (which can be the Id field).

Also, I am unsure if upserting the provider objects will automatically fill in the Ids.  I know it does from Apex, but I am unsure if C# will do so.