Problem:
While testing an existing C# app that connected to our Dynamics 365 environment, we encountered an unusual error after updating the CRM SDK Nuget package used by the app.
System.InvalidCastException: ‘Unable to cast object of type ‘Microsoft.Xrm.Sdk.Entity’ to type ‘XXXX.Xrm.Model.XXXX.’
Here is some sample code to illustrate:
CrmServiceClient conn = new CrmServiceClient("Url=https://myorg.crm6.dynamics.com; Username=XXXXX@XXXXX.com; Password=XXXXXX; authtype=Office365");
IOrganizationService orgService = conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
using (var context = new CrmServiceCtx(orgService))
{
// Do stuff
var lead = context.LeadSet.First(); // Causes error to occur
}
Solution
After some investigation, I discovered that the problem had been caused by a recent change in functionality within the CRM SDK Nuget package Microsoft.CrmSdk.XrmTooling.CoreAssembly.
The SkipDiscovery parameter in the connection string specifies whether to use the Discovery Service. If set to ‘False’ the Discovery Service will be used to find the CRM endpoint address. As of release 9.0.2.7, this value defaults to ‘True’ and causes issues with early bound types.
The solution is to add ‘SkipDiscovery=False’ to your connection string.
CrmServiceClient conn = new CrmServiceClient("SkipDiscovery=False; Url=https://myorg.crm6.dynamics.com; Username=XXXXX@XXXXX.com; Password=XXXXXXX; authtype=Office365");
More information can be found here https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/xrm-tooling/use-connection-strings-xrm-tooling-connect
Hope this helps others out there with the same issue.
17th January 2019 at 2:13 pm
Amazing thank you!
23rd January 2019 at 5:01 am
THANK YOU so much. Lost a few hours on this one today wondering why Early Bound objects were failing with Unable to Case errors all of a sudden.
6th August 2019 at 1:36 am
Many, many thanks for this! Wasted 2 days with blogs saying “Just add _serviceProxy.EnableProxyTypes(); This was the solution and I am so happy because I thought I was going mad.
28th November 2019 at 7:18 am
For reference, I have found that changing the connection string AuthType to OAuth also resolves this issue