web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

C# code to get the parent account

(0) ShareShare
ReportReport
Posted on by

So here is what I need.I have to check for hierarchy for account, if there is parent account id , has to populate on ground level like Account A in the below example.
Then populate account name for account A for example and it will different for each account.
every time go to fetch xml for value of parent account id till parent id becomes null as its top level for whole chain then update that parent account id

Account Name: Account A
PAL: PAL A
ParentAccount Id= Account B


Account Name: Account B
PAL: PAL B
ParentAccount Id= PAL C


Account Name: Account C
PAL: PAL C
ParentAccount Id=


In this example, Account A's Parent account is "Account B" and "Account B's" parent is "Account C". Acccount C does not have a parentAccount Id so it is the top level Account for Account A and Account B.

So for Account A, aac_toplevepal= PAL C and aac_toplevelpalname=Account C
So for Account B, aac_toplevepal= PAL C and aac_toplevelpalname=Account C
So for Account C, aac_toplevepal= PAL C and aac_toplevelpalname=Account C

I have been breaking my head, could not find anything working. Can anyone be kind enough to help me please.

*This post is locked for comments

I have the same question (0)
  • Verified answer
    Ben Thompson Profile Picture
    6,350 on at

    You need a nested / recursive routine - something like this should do (note it's untested - and may have typos as I typed it directly into the answer)

    private EntityReference GetParent(Iservice service, EntityReference account){
    	// if this is the ultimate parent account the next retrieve may not return anything so we set the last result as the ultimate reference
    	
    	var parentAccount=account;
    	var entity=service.retrieve("account", account.Id, new Columnset("parentaccountid"));
    
    	if (entity.contains("parentaccountid"){
    		//there is another record above this one so we retrieve that record by making a nested request to this class
    		parentAccount=GetParent(service, entity.GetParameterValue<EntityReference>("parentaccountid"));
    	}
    
    	// once we have the ultimate parent we can now update the account record
    	var updateAccount = new Entity("account", account.Id);
    	updateAccount["aac_toplevelpal"]=parentAccount;
    	updateAccount["aac_toplevelpalname"]=parentAccount.Name;
    	service.Execute(updateAccount); 
    
    	// finally with the record at this level updated we return to the previous level with the ultimate parent
    	return parentAccount; 
    }


  • Kenneth Leong Profile Picture
    360 on at

    To get the top level pal, you just need a recursive function to retrieve on the parentaccountid, until the parentaccountid is null.

    Note that while you're working your way up the account chain, you're forming a path that you'll go back down later. So after you found the top level pal, while you're exiting, do a svc update on the aac_toplevelpal of each and every one of the children accounts.

    guid topaccount = null;

    function UpdateAccounts(accountid, svc, ctx)

    {

    var parentacc = ctx.account.where(a => a.accountid == accountid).select(a => a.parentaccountid);

    if (parentacc != null) UpdateAccounts(parentacc, svc, ctx);

    else topaccount = parentacc;

    var thisaccount = new account(accountid = accountid, aac_toplevelpal = topaccount);

    svc.update(thisaccount);

    }

  • Community Member Profile Picture
    on at

    2043.Capture.PNG

    Neither of anything I tried so far worked, Please if anyone can help me i shall be obliged. See the screen shot, when we look up for parent account the top level pal name must pull the parent pal and name and account respectively. Kindly help me with the code. I tried the above class but does not seem to work for no idea what reason.

    Tried this as well, but no go. please help me kindly

    try
                {
                    if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                    {
                        Entity processedEntity = (Entity)context.InputParameters["Target"];
                        Entity entityImage = new Entity();
    
                        //if we don't have an entity image no need to go further and return
                        if (!context.PostEntityImages.Contains("AccountPostImage"))
                        {
                            return;
                        }
    
                        entityImage = (Entity)context.PostEntityImages["AccountPostImage"];
                        
                        if(!entityImage.Contains("parentaccountid") || entityImage["parentaccountid"] == null)
                        {
                            processedEntity["acc_accountnumber"] = "YOUR_VALUE";
                            processedEntity["acc_name"] = "YOUR_VALUE";
                            tracingService.Trace($"New account number:{processedEntity["acc_accountnumber"].ToString()} and account name:{processedEntity["acc_name"].ToString()}");
    
                            service.Update(processedEntity);
                        }
    
                        else
                        {
                            tracingService.Trace($" Parent account id is: {((EntityReference)entityImage["parentaccountid"]).Id.ToString()}");
                        }
                    }
                }
    
                catch (Exception ex)
                {
                    tracingService.Trace(System.Reflection.MethodBase.GetCurrentMethod().Name + ": " + ex.Message + (ex.InnerException != null ? "\r\n" + ex.InnerException : string.Empty));
                    throw new InvalidPluginExecutionException(ex.Message);
                }
    
            }
  • Community Member Profile Picture
    on at

    Can anyone please provide me code for a while loop to check if ParentAccountID is set and if set, add that account to list. And Get new account from ParentAccountID field and repeat process in loop.IF account does not have parrentAccountID(means it's a top), update all accounts in list from 1st step by values from top account. Only if someone is kind to provide me the complete code will be appreciated

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans