Advertisements
Home > CRM, Uncategorized > Create a child record by copying mapping fields data from Parent – Using CRM SDK

Create a child record by copying mapping fields data from Parent – Using CRM SDK

Let’s take the OOB Account and Contact related entities.

Whenever we click ‘Add New Contact’ button from the ‘Associated view’ of ‘Account’ form, all the mapping fields data would be copied to ‘New Contact’ form.

Account:

account-form

New Contact Form:

create-contact

This is native CRM behavior, to copy the content from Parent to Child record, using the Relationship ‘Mappings’ to avoid the overhead of manual data entry on child record.

account-and-contact-mappings

What If we have to create a Contact from a console application using CRM SDK and achieve the same behavior?  ‘InitializeFromRequest’ is the answer.

Steps to use ‘InitializeFromRequest’:

  • Instantiate the ‘InitializeFromRequest’
  • Set the Target as ‘Contact’
  • Set the ‘EntityMoniker’ as the reference of parent ‘Account’ which you would want to copy the data from
  • Execute the ‘InitializeFromRequest’
  • From the ‘InitializeFromResponse’, read the Contact object with copied data from Account (**Contact would not be created in CRM at this point**)
  • Fill the other attributes
  • Create the Contact

Source Code:

InitializeFromRequest initialize = new InitializeFromRequest();

// Set the target entity (i.e.,Contact)
initialize.TargetEntityName = “contact”;

// Create the EntityMoniker of Source (i.e.,Account)
initialize.EntityMoniker = new EntityReference(“account”, new Guid(“D4CBEE74-B5E3-E611-8109-C4346BDD8041”));

// Execute the request
InitializeFromResponse initialized = (InitializeFromResponse)orgService.Execute(initialize);

// Read Intitialized entity (i.e.,Contact with copied attributes from Account)
if (initialized.Entity != null)
{
// Get entContact from the response
Entity entContact = initialized.Entity;

// Set the additional attributes of the Contact
entContact.Attributes.Add(“firstname”, “Rajeev”);
entContact.Attributes.Add(“lastname”, “Pentyala”);

// Create a new contact
orgService.Create(entContact);
}

If you put the debugger and watch the ‘initialized.Entity’ you would see the populated fields.

initialized-entity-contact

Post execution of this code, a new Contact would get created with copied data from Account.

contact-form

🙂

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: