Dynamics 365 Tooling – Object of type ‘Microsoft.Xrm.Sdk.Entity’ cannot be converted to type ‘Type’
I think that most of you who are writing applications connecting to Dynamics 365 already wrote thousands of some similar code:
It’s simply connecting to Dynamics 365 using connection string and querying contacts. Connection string looks like that:
<connectionStrings>
<add name=”D365″ connectionString=”Url=https://organization.crm4.dynamics.com; Username=user@domain.com; Password=password; authtype=Office365;” />
</connectionStrings>
For many years it was working like a charm. If you have upgraded to latest XrmTooling version which is 9.0.2.7 at the time of writing this post, this code will throw exception:
System.ArgumentException: ‘Object of type ‘Microsoft.Xrm.Sdk.Entity’ cannot be converted to type ‘Contact’.’
Some of you may remember this error and while googling for it you will come across some posts from years ago when it was simply a mistake of not calling “EnableProxyTypes” function. This is from times when we had to manually create OrganizationServiceProxy object. Without calling “EnableProxyTypes” service did not know how to deserialize result into proper object (so Contact in this example). Some more details were provided by James Wood and myslef in this StackOverflow question
So what is the fix, because I don’t believe anybody will rewrite the code to cast all Entities to Contacts manually. Fortunately there is a quick fox for that, simply add SkipDiscovery=false to your query string, because it looks like it’s default value changed from false to true between versions 9.0.2.5 and 9.0.2.7. So your connection string should look like this:
<connectionStrings>
<add name=”D365″ connectionString=”Url=https://organization.crm4.dynamics.com; Username=user@domain.com; Password=password; authtype=Office365; SkipDiscovery=false;” />
</connectionStrings>
And it should work 🙂