Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics 365 | Integration, Dataverse...
Answered

Custom Entity update: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary

Posted on by 25

Hi,

A Newbie here! I am trying my hands on Dynamics programming and testing out a basic code to update a custom entity that I created in a plugin.

Task I am trying to code is: when "sales rep" is assgined to to a zone (custom field "crdc2_repinzoneid") set field "status" (type:two option, name:crdc2_status) to "assigned"  (See screenshot below)

Step is registered to fire on Entity Update at PostOperation (see screenshot below).

This is what I did in plugin code:

1. Create a new entity "sales rep" using context.PrimaryEntityId

Entity salesRep = new Entity("crdc2_salesrep", context.PrimaryEntityId);

2. Create attribute which needs to be updated:

salesRep["crdc2_status" = entity["crdc2_repinzoneid" == null ? false : true; //set value

3. Fire Update

service.Update(salesRep);

I debugged the plugin and at #3 I get the exception  System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary

I fail to understand the reason here. The name "crdc2_status" exists in "crdc2_salesrep" entity.

What am I missing here!

Code:

public void Execute(IServiceProvider serviceProvider)
    {
      //Extract the tracing service for use in debugging sandboxed plug-ins.
      ITracingService tracingService =
          (ITracingService)serviceProvider.GetService(typeof(ITracingService));
      IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));

      tracingService.Trace("SalesRepAssignedPlugin plgin: start execution4");
      if (context.InputParameters.Contains("Target") &&
          context.InputParameters["Target"] is Entity)
      {
        try
        {
          Entity entity = (Entity)context.InputParameters["Target"];
          var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
          var service = serviceFactory.CreateOrganizationService(context.UserId);

          if (entity.LogicalName != "crdc2_salesrep")
            return;

          //create new entity with only fields that needs to be updated
          Entity salesRep = new Entity("crdc2_salesrep", context.PrimaryEntityId);
          //create attrib to update
          salesRep["crdc2_status"] = entity["crdc2_repinzoneid"] == null ? false : true;            //set value

          service.Update(salesRep);
        }
        catch (FaultException ex)
        {
          tracingService.Trace("SalesRepAssignedPlugin plgin ex: {0}", ex.ToString());
          throw new InvalidPluginExecutionException("SalesRepAssignedPlugin plgin:siyapa!", ex);
        }
        catch (Exception ex)
        {
          tracingService.Trace("SalesRepAssignedPlugin plgin ex: {0}", ex.ToString());
          throw;
        }

      }

Custom Entity Fields

sales-rep-fields.jpg

Plugin step:

step.jpg

Thanks,

Jags

  • LuHao Profile Picture
    LuHao 40,872 on at
    RE: Custom Entity update: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary

    Glad it was resolved.

  • Verified answer
    Jags8 Profile Picture
    Jags8 25 on at
    RE: Custom Entity update: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary

    I was finally able to resolve this!

    1. I ended up using PostImage to pick the field value being updated:

    2. Another thing which I learned is that when a lookup field is set to blank then the attribute value, instead of being NULL, is not included in image at all!

    so this check throws an exception when lookup field is not set:

    postImageRep["crdc2_repinzoneid"] == null

    correct code to check for blank/empty lookup field is 

    postImageRep.Attributes.Contains("crdc2_repinzoneid") == false;

    Thanks!

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!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,198 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans