In Dynamics 365 you are able to create a 1 to N, N to 1 or N to N relationship between two Entities. With this you also have the option to create a self-referential relationship. The screenshot below is an example of an N to N self-referential relationship created on the Account entity with the relationship name being new_account_account.

image

When retrieving records using this N to N relationship via the SDK you’ll notice that you need to do something a little different. The screenshot below shows the link entity code needed for this retrieve which starts off the same as usual, using a QueryExpression. The first things to note are the entityOne, entityTwo and relationship variables which you can simply get from CRM as shown in the screenshot above. The next thing to note are the id variables ‘accountidtwo’ and ‘accountidone’. The reason for this is because both sides of this relationship will have ‘accountid’ as their id, so Dynamics 365 in the background will use the appended ‘two’ and ‘one’ to identify which account is which.

image

After this you can add any columns you need to using .Columns.AddColumn(s) or add the order, etc. Then once you’ve added everything you need to retrieve to the QueryExpression in LinkEntity objects, you’re able to retrieve records as per usual using the SDK’s RetrieveMultiple function.