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.
- Solved: Build Errors Not Showing in VS 2022 - 21st November 2024
- How To: Configure VSCode to Trust Self-Signed Certs - 16th August 2024
- Solved: GitHub Actions – HTTP 403: Resource not accessible by integration - 13th June 2024
Amazing thank you!
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.
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.
For reference, I have found that changing the connection string AuthType to OAuth also resolves this issue