Search code examples
c#dynamics-crmcrmdynamics-crm-onlinefetchxml

Getting entity attribute from CRM - Specified cast is not valid


I'm using fetchXML to query MS CRM and everything seems OK except when I try to retrieve an attribute of an entity that is a unique identifier.

Guid contactID = entity.GetAttributeValue<Guid>("sb_contactid");

Results in:

Specified cast is not valid.

When I inspect the entity before trying to get the attibute values I can see the value (and also that is a 'entityReference' is this relevant?).

enter image description here

enter image description here

I have also tried:

var contactID = (Guid)entity.Attributes["sb_contactid"];

Other entity attributes of various types are retrieved without issue and as above, can see the value of the attribute when inspecting the entity - how do I get it out?


Solution

  • The type of sb_contactid is EntityReference. You won't be able to cast this to Guid type.

    But you can get the Guid from the EntityReference.

    Guid contactId = entity.GetAttributeValue<EntityReference>("sb_contactid").Id;