Monday, October 3, 2016

Create Many to Many Records in CRM using c#

I have written an article of how this can be done in 2011. The class that was used to do this has been deprecated, so putting down below how the new class would work.


The code is taken from the below link from Microsoft. It contains the both associate as well as disassociates functionalities.


Although this has been done for account and contact, the below code can be used for any entities which are having many to many relationship. There are 3 accounts being associated with one contact record. It can be a single account record and the code would still work.

// Associate the accounts to the contact record.

// Create a collection of the entities that will be
// associated to the contact.
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account1Id));
relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account2Id));
relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account3Id));

// Create an object that defines the relationship between the contact and account.
Relationship relationship = new Relationship("account_primary_contact");


//Associate the contact with the 3 accounts.
_service.Associate(Contact.EntityLogicalName, _contactId, relationship,
    relatedEntities);

Console.WriteLine("The entities have been associated.");

//Disassociate the records.
_service.Disassociate(Contact.EntityLogicalName, _contactId, relationship,
    relatedEntities);


 Also the below code works fine as well. Again this was taken form a Microsoft link.


AssociateRequest teamToProfile = new AssociateRequest
{
    Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId),
    RelatedEntities = new EntityReferenceCollection
    {
        new EntityReference(Team.EntityLogicalName, _teamId)
    },
    Relationship = new Relationship("teamprofiles_association")
};
 
// Execute the request.
_serviceProxy.Execute(teamToProfile);


No comments:

Post a Comment

Retrieving Calendar of a Bookable Resource in Dynamics

There are occasions where we need to retrieve working days and working times of a resource in Dynamics grammatically. This is quite possible...