Dela via


Use the Entity class to add or update associations between related records

 

Applies To: Dynamics CRM 2015

In Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update, you can use the IOrganizationService. Associate and IOrganizationService.Disassociate methods to create and remove associations between related records.

To create an association, you first determine the unique ID of the target entity to be associated. You then create a collection of entities to be associated with the target entity. Next, you define a relationship between the entities in the collection and the target entity. Finally, you pass this information to the Associate method. The same information is passed to the Disassociate method when you remove an association.

The following code example shows how to create associations between related records and how to disassociate them.

// The account ID would typically be passed in as an argument or determined by a query.
// The contact ID would typically be passed in as an argument or determined by a query.
// Associate the accounts to the contact record. 
//Create a collection of the entity ids that will be associated to the contact.
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
relatedEntities.Add(new EntityReference("account", _account1Id));
relatedEntities.Add(new EntityReference("account", _account2Id));
relatedEntities.Add(new EntityReference("account", _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.
_orgService.Associate("contact", _contactId, relationship, relatedEntities); 
Console.WriteLine("The entities have been associated."); 
//Disassociate the records.
_orgService.Disassociate("contact", _contactId, relationship, relatedEntities); 
Console.WriteLine("The entities have been disassociated.");

See Also

Use the late bound entity class in code
Use the Entity class for create, update and delete
Entity relationship behavior
Sample: Create, retrieve, update, and delete (late bound)

© 2016 Microsoft. All rights reserved. Copyright