Shane Bartholomeusz

Geek and lover of all things tech related

Solved: Dynamics 365 Unable to Cast Object Error

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.’

Dynamics 365 logo

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.

Shane Bartholomeusz

4 Comments

  1. Amazing thank you!

  2. 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.

  3. 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.

  4. For reference, I have found that changing the connection string AuthType to OAuth also resolves this issue

Leave a Reply

© 2024 Shane Bartholomeusz

Theme by Anders NorenUp ↑