Search code examples
pluginsdynamics-crmcrmdynamics-crm-4

How to iterate in 1:N relationship in Dynamics CRM4 C# Plugin


Our Account entity has a 1:N relationship with 'BookingAccount', a custom Entity. The name of the relationship is new_Account_new_BookingAccount. In a plug-in, if I try to iterate the collection

foreach (new_BookingAccount ba in myAccount.new_Account_newBookingAccount)
{
    ...
}

it's null - even when there are related BookingAccounts.

Am I supposed to re-query for the BookingAccounts or can I call some 'populate' method on the collection property? If so how is the best way to do this? And what's the point of the collection property if you can't iterate it.

Thanks for any help in advance.


Solution

  • Ah - the collection needs to be loaded explicitly:

    orgContext.LoadProperty(account, "new_BookingAccount_new_ExternalCode");
    foreach (new_BookingAccount ba in myAccount.new_Account_new_BookingAccount)
    {
        ...
    }
    

    (Though this can't be done if the accouont is a new entity, so needs some sort of check beforehand):

    if (account.CreatedOn == null)
        return;
    

    Seems like a lot of work for simple collection iteration