1
votes

I have a strange problem, I have tons of entities and I have a XrmSchema.cs generated by CRMSvcUtil in my crm system which worked for me pretty good, especially while using queries and converting them to entity objects in the code. This convertion method worked perfect for all entites except one, I keep getting System.InvalidCastException: Unable to cast object of type 'Microsoft.Xrm.Sdk.Entity' error for this one entity. Here's the following code segment that generates it, it throws the exception in the toList() method:

 public List<etel_productcharacteristic> RetrieveCharacteristic(Guid characteristicId)
        {
            using (XrmDataContext context = new XrmDataContext(CRMConnection.OrganizationService))
            {   
                var query = from characteristic in context.etel_productcharacteristicSet
                            where characteristic.etel_productcharacteristicId == characteristicId && characteristic.statecode.Value == etel_productcharacteristicState.Active
                            select characteristic;
                return query.ToList();


            }
        }

Can anybody point me what might be wrong with this code. By the way all the solutions that I read on the on the internet suggests use of enableproxy method. In my case Enableproxy method is being called while organizationservice is being initialized, so it does not look like the culprit. And all the other conversion work fine in my plugin there has to be something wrong with this one.

1
Did you already try to Retrieve a single record of etel_productcharacteristic by Id? I'd also try a late-bound query to see if the problem is located in the generated XrmSchema.Filburt
Late bound query didn't work, but retrieving a single record helped. Thanks for the suggestion.erin c

1 Answers

2
votes

You need to change this line:

where characteristic.etel_productcharacteristicId == characteristicId && characteristic.statecode.Value == etel_productcharacteristicState.Active

to read

where characteristic.etel_productcharacteristicId.Id == characteristicId && characteristic.statecode.Value == (int)etel_productcharacteristicState.Active

Honestly, you'll need to double-check me on the (int) cast, as it may not be required - I just don't have code in front of me to verify.