Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Set Lookup value into Null

Posted on by 460

Hello,

I have two entities, called "Project" and "Program". 

In those both entities, also have same field, which is "End Customer" with type lookup to Account.

the question is, how to set lookup value "End Customer" into null in "Program" entity, if "Project" have null value?

this is my code :

// <copyright file="ChangeEndCustomer.cs" company="Microsoft">
// Copyright (c) 2017 All Rights Reserved
// </copyright>
// <author>Microsoft</author>
// <date>11/15/2017 4:34:10 PM</date>
// <summary>Implements the ChangeEndCustomer Workflow Activity.</summary>
namespace MFS_SOLUTION.MFS_WORKFLOW
{
    using System;
    using System.Activities;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Query;
    using System.Linq;

    public sealed class ChangeEndCustomer : CodeActivity
    {
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered ChangeEndCustomer.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                executionContext.ActivityInstanceId,
                executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace("ChangeEndCustomer.Execute(), Correlation Id: {0}, Initiating User: {1}",
                context.CorrelationId,
                context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                // TODO: Implement your custom Workflow business logic.
                Entity entity = null;

                if (context.InputParameters != null && context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    entity = (Entity)context.InputParameters["Target"];
                }
                else
                {
                    entity = service.Retrieve(context.PrimaryEntityName, ((Guid)context.PrimaryEntityId), new ColumnSet(true));
                }

                Guid ProjectID = new Guid();
                Guid EndCustomerID = new Guid();
                Guid ProgramID = new Guid();
                Guid NullCustomerID = new Guid();

                Entity RetrieveProject = service.Retrieve("ibiz_project", entity.Id, new ColumnSet(true));

                ProjectID = RetrieveProject.GetAttributeValue<Guid>("ibiz_projectid");
                EndCustomerID = RetrieveProject.GetAttributeValue<EntityReference>("ibiz_endcustomer").Id;
                
                ConditionExpression CheckProject = new ConditionExpression();
                CheckProject.AttributeName = "ibiz_project";
                CheckProject.Operator = ConditionOperator.Equal;
                CheckProject.Values.Add(ProjectID);

                FilterExpression FilterProject = new FilterExpression();
                FilterProject.Conditions.Add(CheckProject);

                QueryExpression queryProject = new QueryExpression("ibiz_program");
                queryProject.ColumnSet = new ColumnSet(true);
                queryProject.Criteria.AddFilter(FilterProject);

                EntityCollection resultProject = service.RetrieveMultiple(queryProject);

                if (resultProject.Entities.Any())
                {
                    foreach (Entity eProject in resultProject.Entities)
                    {
                        ProgramID = eProject.GetAttributeValue<Guid>("ibiz_programid");

                        if (EndCustomerID != null)
                        {
                            Entity ProgramToUpdate = new Entity("ibiz_program");
                            ProgramToUpdate["ibiz_programid"] = ProgramID;
                            ProgramToUpdate["ibiz_endcustomer"] = new EntityReference("account", EndCustomerID);
                            service.Update(ProgramToUpdate);
                        }
                        else
                        {
                            Entity ProgramToUpdate = new Entity("ibiz_program");
                            ProgramToUpdate["ibiz_programid"] = ProgramID;
                            ProgramToUpdate.Attributes.Add("ibiz_endcustomer", null);
                            service.Update(ProgramToUpdate);
                        }
                    }
                }
            }
            catch (FaultException<OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }

            tracingService.Trace("Exiting ChangeEndCustomer.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
    }
}


the error saying nullreferenceexception, when I tried to remove value in "Project" entity.

*This post is locked for comments

  • xcode17 Profile Picture
    xcode17 460 on at
    RE: Set Lookup value into Null

    Hi HIMBAD and Ravi,

    many thanks for the help. Yeah, I can use that way.

  • Suggested answer
    Iswarya Profile Picture
    Iswarya 1,345 on at
    RE: Set Lookup value into Null

    Hi,

    Entity entity = (Entity)context.InputParameters["Target"];

                   if (entity.LogicalName != "Project")

                   {

                       return;

                   }

    Entity ProgramUpdation = new Entity();

    ProgramUpdation .LogicalName = "Program";

    ProgramUpdation["ibiz_programid"] = ProgramID;

         if (entity.Attributes.Contains("End Customer_Project") && entity.Attributes["End Customer_Project"] != null)

                       {

                           EntityReference EndCustomer= (EntityReference)entity.Attributes["End Customer_Project"];

                           ProgramUpdation[End Customer_Program]=EndCustomer;

                       }

    service.Update(ProgramUpdation);

    it only update lookup field of Program(if Project entity lookupfield contain value ).other wise it will set null value

  • Verified answer
    RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: Set Lookup value into Null

    Hi,

    Comment the statement " EndCustomerID = RetrieveProject.GetAttributeValue<EntityReference>("ibiz_endcustomer").Id;"

    and change "if (EndCustomerID != null)" to "if (RetrieveProject.Contains("ibiz_projectid"))"

    And while setting  replace "ProgramToUpdate["ibiz_endcustomer"] = new EntityReference("account", EndCustomerID);" with "ProgramToUpdate["ibiz_endcustomer"] = RetrieveProject.GetAttributeValue<EntityReference>("ibiz_endcustomer")" as this an entity reference, you don't need to create a instance of entity reference

    I hope this helps. If my post answers your question, please mark as "Verified"

  • Verified answer
    Mahendar Pal Profile Picture
    Mahendar Pal 45,095 on at
    RE: Set Lookup value into Null

    Setting null is ok here, but you should validate using Contains before getting value for example

    if(RetrieveProject.Contains("ibiz_projectid"))

    {

    //read value

    }

  • DlwK Profile Picture
    DlwK 605 on at
    RE: Set Lookup value into Null

    I think this line might throw the error:

    EndCustomerID = RetrieveProject.GetAttributeValue<EntityReference>("ibiz_endcustomer").Id;

    If that ibiz_endcustomer attribute has no value, you cannot get the Id property of it?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,240 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,149 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans