0

I'm getting error when I try to execute the last line in this reply. I run the following code:

QueryExpression query = new QueryExpression
{
  LogicalName = "contact",
  ...
}

BusinessEntityCollection response = ServiceProxy.RetrieveMultiple(query);
Logify("count: " + response.BusinessEntities.Count);
BusinessEntity piff= response.BusinessEntities.First();
Logify("piff: " + (piff != null));

DynamicEntity poof = response.BusinessEntities.First() as DynamicEntity;
Logify("poof: " + (poof != null));

The count is 1, so the call is performed correctly and yields something. According to the log, piff isn't null, so it contains something. However, after the conversion (which is required in order to access the fields of the entity), I get it to be null (or I get an Exception when trying to explicitly cast the shabang).

The exception is:

Unable to cast object of type 'Microsoft.Crm.SdkTypeProxy.contact' to type 'Microsoft.Crm.Sdk.DynamicEntity'.

What to do?!

Community
  • 1
  • 1
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
  • When you use `as ` there are only 2 outcomes. Either type, or null. The conversion is failing so `poof` is null. Are you sure that a `BusinessEntity` can be cast as a `DynamicEntity`? – crthompson May 15 '14 at 15:26
  • @paqogomez I'm sure it can't be because the computer says so. However, it's **supposed** to work as the example I link to shows. In either case, I need to access a field on the fetched entity and I'm not sure how to if I can't cast the stupid thing. – Konrad Viltersten May 15 '14 at 15:28
  • 1
    2 questions. First, does `BusinessEntity` inherit from `DynamicEntity`. Second, if you call response.BusinessEntities two times in a row, does it work? To test the second question, can you try poof before piff? – DavidG May 15 '14 at 15:43
  • the exact exception you get? – Guido Preite May 15 '14 at 18:37
  • @DavidG #1: Yes, as far I'm informed. #2: Yes, even if *First* would remove the first element, I've tested with responses of multiple entities. – Konrad Viltersten May 15 '14 at 21:19
  • @GuidoPreite Kindly, see the addition in the question. – Konrad Viltersten May 15 '14 at 21:34

1 Answers1

1

The answer is to use RetrieveMultipleRequest. Reworked code:

QueryExpression query = new QueryExpression
{
    LogicalName = "contact",
    ...
}

RetrieveMultipleRequest rmr = new RetrieveMultipleRequest()
{
    Query = query,
    ReturnDynamicEntities = true
};

RetrieveMultipleResponse rmrresp = ServiceProxy.Execute(rmr) as RetrieveMultipleResponse;
BusinessEntityCollection response = rmrresp.BusinessEntityCollection;
Logify("count: " + response.BusinessEntities.Count);
BusinessEntity piff= response.BusinessEntities.First();
Logify("piff: " + (piff != null));

DynamicEntity poof = response.BusinessEntities.First() as DynamicEntity;
Logify("poof: " + (poof != null));
Andrew Butenko
  • 5,048
  • 1
  • 14
  • 13