Dynamics CRM: Populate Data using InitializeFrom Function

Do you notice when we create a Lead and qualify it in Dynamics CRM, the out-of-the-box feature will convert the Lead to Contact (all the data that was input in Lead, automatically populated in the Contact)? And sometimes, we are also being requested to make the same feature (mapping the data from one table to another table). InitializeFrom function can help us to do it and below is my observation about the function.

The Observation

I’m running below source code to convert the Lead (from sample data), to Contact using the InitializeFrom function:

using System;
using System.Web.Configuration;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;

namespace CrmCheck
{
    class Program
    {
        static void Main(string[] args)
        {
            CrmServiceClient.MaxConnectionTimeout = TimeSpan.FromHours(3);
            var connectionString = WebConfigurationManager.AppSettings["connectionString"];
            var client = new CrmServiceClient(connectionString);

            var request = new OrganizationRequest("InitializeFrom");
            request["EntityMoniker"] = new EntityReference("lead", new Guid("71b63ce4-4b56-ec11-8f8f-00224825d652"));
            request["TargetEntityName"] = "contact";
            request["TargetFieldType"] = TargetFieldType.All;

            var result = client.Execute(request);
           
            Console.ReadKey();
        }
    }
}

The result shows many attributes that are mapped automatically (I’m using TargetFieldType.All for this example):

InitializeFrom Lead to Contact Result

Create New Table

From the above result, it makes me wonder how it works. My initial thoughts are that it will be based on the attribute name. So I created the below table to test the function:

Create a new table with new_firstname and new_lastname attributes

Then I run this code which results in the below error:

When I set the TargetEntityName to new_testmapping, it throws “There is no entity map defined for the given entities”

Data Mapping

We got an error “There is no entity map defined for the given entities” which lead me to “remember” about Data Mapping in the Dynamics CRM. First, we need to create a lookup from the table that we want (new_mapping.new_leadid):

Mandatory to create Lookup from the Source Table

Unfortunately, we need to use the classical UI to create the data mapping. Go to Solution > the Lead (or you can go to the target Table) > Find the correct mappings (either in 1:N or N:1, select the correct relationship) > then you can create the mapping (both tables need to have the same attribute data type):

Create Data Mapping From Source to Target Table

Once you have already created the Data Mapping, don’t forget to Publish All The Customization.

Summary

If you run again the below code, you will see the result already (the second method is using InitializeFromRequest from the SDK):

using System;
using System.Web.Configuration;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;

namespace CrmCheck
{
    public static class OrganizationResponseExtensions
    {
        public static T Cast<T>(this Microsoft.Xrm.Sdk.OrganizationResponse response)
            where T : OrganizationResponse
        {
            var newClass = Activator.CreateInstance<T>();
            newClass.Results = response.Results;

            return newClass;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CrmServiceClient.MaxConnectionTimeout = TimeSpan.FromHours(3);
            var connectionString = WebConfigurationManager.AppSettings["connectionString"];
            var client = new CrmServiceClient(connectionString);

            var request = new OrganizationRequest("InitializeFrom");
            request["EntityMoniker"] = new EntityReference("lead", new Guid("71b63ce4-4b56-ec11-8f8f-00224825d652"));
            request["TargetEntityName"] = "new_testmapping";
            request["TargetFieldType"] = TargetFieldType.All;

            var result = client.Execute(request);

            var request2 = new Microsoft.Crm.Sdk.Messages.InitializeFromRequest
            {
                EntityMoniker = new EntityReference("lead", new Guid("71b63ce4-4b56-ec11-8f8f-00224825d652")),
                TargetEntityName = "new_testmapping",
                TargetFieldType = TargetFieldType.All
            };            
            var result1 = client.Execute(request).Cast<Microsoft.Crm.Sdk.Messages.InitializeFromResponse>();

            var id = client.Create(result1.Entity);
            Console.WriteLine($"Created record id {id}");
            Console.ReadKey();
        }
    }
}

The result:

The data populated correctly

In this blog post, we just learned how to use the InitializeFrom function. The return result will automatically populate all the data based on the Data Mapping. But we still need to call OrganizationService.Create/Update (depends on your scenario) to create/update the row.

Happy CRM-ing!

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.