In this blog, I will demonstrate how to set a value for the owner field on the record creation in Child entity (Contact) from Parent entity (Account) plugin, using C# in Dynamics CRM.
Creating a Plugin
The code snippet given below shows how the owner field of the newly created record is being set but one thing, which we need to know is this process can be done only during the pre-creation stage. If we are trying to update the owner field of a record, which is already created, then we may need to use AssignRequest, as shown in section 2.
Section:1
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Microsoft.Xrm.Sdk;
- using Microsoft.Xrm.Sdk.Messages;
- using System.ServiceModel.Description;
- using Microsoft.Xrm.Sdk.Query;
- using System.Runtime.Serialization;
- namespace projectname.fieldmappings {
- public class FieldMappings: IPlugin {
-
- public void Execute(IServiceProvider serviceProvider) {
-
- ITracingService tracingService = (ITracingService) serviceProvider.GetService(typeof(ITracingService));
-
- Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
- serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
- IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof(IOrganizationServiceFactory));
- IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.UserId);
-
- if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) {
-
- Entity entity = (Entity) context.InputParameters["Target"];
-
- Entity ContactDetails = new Entity("Contact");
-
- EntityReference owner = new EntityReference();
- owner.Id = ((EntityReference)(entity.Attributes["primarycontactid"])).Id;
- owner.LogicalName = ((EntityReference)(entity.Attributes["primarycontactid"])).LogicalName;
- ContactDetails["ownerid"] = owner;
- orgSvc.Create(ContactDetails);
- }
- }
- }
- }
Please refer to this link to register and debug the plugin.
Section 2
To update the owner field of the existing record, use the code given below.
-
- AssignRequest assignowner = new AssignRequest {
- Assignee = new EntityReference(SystemUser.EntityLogicalName, _otherUserId),
- Target = new EntityReference(Account.EntityLogicalName, _accountId)
- };
-
- orgService.execute(assignowner);
Output
Account
Primary Contact: Dave Adam
Contact:
Owner: Dave Adam
It does not matter who creates the contact from the account but the plugin will set the primary contact as an owner.
Hope, this blog may be helpful to you.