Wednesday, June 26, 2013

CREATING RECORDS WITH A RELATIONSHIP

We had to create a record with a relationship in CRM 2011. The trick was that in the form there were no option for the user to associate the two entities but still the relationship was present. For example, a contact was having categories associated, but in the form there were no option for the user to select the contact when the category was created.
We were trying to create the category via a plugin. We were able to achieve the same by creating the category first and then associating the category to the contact using AssociateRequest. Below is the code snippet for the same.

Entity category = new Entity("new_category");
//Create the reference entity object for the category.
EntityReference categoryReference = new EntityReference("category", categoryId);
//Add that attribute to the entity.
category.Attributes.Add("category", categoryReference);
//Create the category and get the GUID for the new one.
Guid categoryCreated = service.Create(category);
//Associate the created category with the contact.
AssociateRequest associateRequest = new AssociateRequest
{
Target=new EntityReference("contact",contactId),
RelatedEntities=new EntityReferenceCollection
{
    new EntityReference("category",categoryCreated)
},
Relationship=new Relationship(relationshipName)
};
service.Execute(associateRequest);


 



 
 

No comments:

Configuration for CRM Plugins

CRM plugins are always great feature where we can automate many functionality which we cannot automate from user interface. But almost eve...