Getting Error: Unable to cast object of type 'System.String' to type 'Microsoft.Xrm.Sdk.EntityReference'.

May 29, 2013 at 7:56 AM
Hello there,

I built an XML, but when I want to execute it, it throws the error
Unable to cast object of type 'System.String' to type 'Microsoft.Xrm.Sdk.EntityReference'
Generic SQL error.
Here is the code, I want to execute:
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
<entity name="prefix_cmp_act">
<link-entity name="prefix_cmp_list" from="prefix_cmp_listid" to="prefix_cmp_list_id" alias="al">
<link-entity name="prefix_cmp_list_prefix_consumption_point" intersect="true" visible="false" to="prefix_cmp_listid" from="prefix_cmp_listid">
<link-entity name="prefix_consumption_point" to="prefix_consumption_pointid" from="prefix_consumption_pointid" alias="cp.prefix_consumption_point">
<attribute name="prefix_streetname" alias="cp.prefix_consumption_point.prefix_streetname"/>
<attribute name="prefix_houseno" alias="cp.prefix_consumption_point.prefix_houseno"/>
<attribute name="prefix_zip_code" alias="cp.prefix_consumption_point.prefix_zip_code"/>
<attribute name="prefix_city" alias="cp.prefix_consumption_point.prefix_city"/>
<attribute name="prefix_accountid" alias="cp.prefix_consumption_point.prefix_accountid"/>
<link-entity name="account" from="name" to="itvt_accountid" alias="ac.account">
<attribute name="name" alias=""/>
<filter type="and">
<condition attribute="prefix_cmp_actid" operator="eq" uiname="Erzeugung und Versand der Kampagnen-Dokumente" uitype="prefix_cmp_act" value="{8548C751-9FB0-E211-92BD-00155D01DA6D}" />
However, when I delete the last lookup from this FetchXML, it works
This is the LookUp
<link-entity name="account" from="name" to="itvt_accountid" alias="ac.account">
<attribute name="name" alias=""/>
Is something wrong with my code or something else?
Dec 31, 2013 at 12:35 PM
name is a string field in your fetchxml.
In FetchXml when we define link entity we specify EntityReference/Guid in 'from' and 'to' attributes for linking two entities.
so if you change your link entity fetch to the below it will surely work.
<link-entity name="account" from="accountid" to="itvt_accountid" alias="ac.account">
      <attribute name="name" alias=""/>
Apr 24, 2014 at 1:57 AM
I just came across this same issue. After tracing through the code, it turned out to be a problem with aliased values..

Find the following line of code in the getValuefromAttribue function:

return getValuefromAttribute(((Microsoft.Xrm.Sdk.AliasedValue)p).Value.ToString());

It needs to be changed to:
return getValuefromAttribute(((Microsoft.Xrm.Sdk.AliasedValue)p).Value);

The .ToString() actually returns the type name of the object as opposed to the actual object