Search code examples
dynamics-crmdynamics-365dynamics-365-sales

EntityReference is not working with AlternateKey


I created an alternate key on Contact Entity that name is obs_key.

Here is the screenshot of the key definition.

Alternate Key Definition

and then I try to create EntityReference object like below;

string customerCode = entity.GetAttributeValue<string>("obs_customer_code");
EntityReference contactRef = new EntityReference("contact", "obs_key", customerCode);

But I'm getting errors. Error says

Invalid EntityKey Operation performed : Entity contact does not contain an attribute named obs_key

How can I fix the problem?


Solution

  • Microsoft's documentation says you need to set keyname and keyvalue like below.

    public EntityReference (string logicalName, string keyName, object keyValue);
    

    Documentation Link

    My alternate key name is : obs_key

    the field dependent with alternate key : obs_id

    But it didn't work. I try to set the field name, not the key name and it works.

    EntityReference contactRef = new EntityReference("contact", "obs_id", customerCode);