Tuesday, February 4, 2014

How to programmatically initilize mapped attributes when you create a new record

Hi Guys,

When you have a 1:N relationship in Dynamics CRM 2011/2013 between two entities such as Account and Contact, this relationship can be respresented by a subgrid of contacts on the account form.

If this relationship contains some mapping attributes, and you want to create a contact from this subgrid, the new contact record will contains all mapped attributes with data from the parent account record. but when you want to create this record programmatically using a plugin, this mapping will dont work.

To force this mapping using the code, you need to use InitializeFromRequest - InitializeFromResponse.

The InitializeFromRequest - InitializeFromResponse message allow CRM to initialize all mapping attribute between source and target entities.

the InitializeFromResponse object contain a member called Entity that contains a memory image of the target entity record with all mapped attributes. So you need to get this Entity object and call service.create().

There is an example that illustrate this case :

  // Allow CRM to initialize all mapping attributes between account and contact entities.
  InitializeFromRequest initializeFromRequest = new InitializeFromRequest();
  initializeFromRequest.EntityMoniker = new EntityReference("account", accountRecord.Id);
  initializeFromRequest.TargetEntityName = "contact";
  initializeFromRequest.TargetFieldType = TargetFieldType.All;

  InitializeFromResponse initializeFromResponse = (InitializeFromResponse)service.Execute(initializeFromRequest);


  // Create a new contact record with all initialized mapped attributes
  Entity contact = initializeFromResponse.Entity;
  service.Create(contact);



have a nice day.

N.JL

1 comment: