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; [email protected]; 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; [email protected]; 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

G’day, I’m a technical solutions consultant based in Perth, Australia that specialises in the Microsoft technology stack, including .NET, Dynamics 365, Azure and general web development etc.

This blog is my place to share my thoughts, helpful solutions and just random nerdy stuff.
Shane Bartholomeusz

Latest posts by Shane Bartholomeusz (see all)

3 thoughts on “Solved: Dynamics 365 Unable to Cast Object Error

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

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

Leave a Reply