CRM 2011/2013 – System.InvalidCastException: Unable to cast object of type ‘Microsoft.Xrm.Sdk.Entity’ to type

I had an odd error today whilst developing and it turned out to be a very frustrating few hours.

I was writing a plugin which would work for Lead and Contact and because of this I was using a mixture of late binding and early binding.

The late binding was used because I was writing a plugin to fire on update and create of a lead/contact. It was working out the salutation. It was different entities but the same field names.

So I used Entity object and late binding to get the values of a 2 field, I was using these values to retrieve the data from another entity which was early bound.

My personal preference is to use early binding because I find the code is easier to read, it’s also a lot easier to  write because you can use intellisense to get the fields rather than looking at the exact field name.  The other benefit of early binding is you remove any syntax errors from run time and casting/conversion errors are found whilst compiling.


Casting error

It was working fine, my queryexpression was returning some records but when I tried to cast the records from Entity to my early bound entity I was getting

System.InvalidCastException: Unable to cast object of type ‘Microsoft.Xrm.Sdk.Entity’ to type…

Now this is a common problem people have had with early bound types

Usually to resolve the problem you need to add one of the lines below to say, yes – enable ProxyTypes for my CRMService (IOrganizationService)

_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

But looking at my code I could see I already had this


Duplicate Entities Reference

Then whilst building the project I was getting this error

Duplicate ‘Microsoft.Xrm.Sdk.Client.ProxyTypesAssemblyAttribute’ attribute

What the heck does this mean, more internet searching

This brought me to this page

and an answer from CRM MVP Gonzalo

Reference assemblies are not supported in CRM (at least officially) and they can always cause headaches, I strongly discourage them. What you can do is include the generated code from crmsvcutil.exe into each of your plugin assemblies and that should work. You can also include this line of code in your plugin assembly (which is included in the generated code):

It seems the problem was due to someone trying to reference Entities class from inside a dll and this doesn’t really work and a better solution is to add the entities class, so it’s included in the plugin dll (and you don’t need to go outside to another DLL to get the entities.class)

Visual Studio pointed me to this line with it’s error

[assembly: Microsoft.Xrm.Sdk.Client.ProxyTypesAssemblyAttribute()]

I then noticed I had two references to Entities (early binding file)

using Hosk.Dynamics.Crm..Entities;
using Microsoft.Xrm.Sdk.Query;
using Hosk.Dynamics.Crm..ContactLead.Entities;


Now things started to become clear, when I looked at the entities file before it didn’t have the entity I wanted so I regenerated the entities file using the CRM Developer toolkit.

The downside of using the CRM Developer toolkit to do this is it creates an entities file for all of them.  I did notice before there only seemed to be a small selection of the entities.

I then found there was a separate project with the crmsvcutil.exe, for those of you who don’t know what this is, it’s the command line tool Microsoft has created for creating the early bound Entities file.

I have used and written about this before


Only Create the Entities you need

The crmsvcutil.exe takes some config values which allows you to specify which entities you want to create early binding for.

You can pass some variables to the exe

<?xml version=”1.0″ encoding=”utf-8″ ?>

<add key=”o” value=”Entities.cs“/>
<add key=”url” value=”http://<CRM Server url/>CRMORGNAME/XRMServices/2011/Organization.svc“/>
<add key=”namespace” value=”Hosk.Entities”/>
<add key=”codewriterfilter” value=”BasicFilteringService,CrmSvcUtilExtensions”/>


Then a text file called EntitiesToBuild.txt and in this file were all the entities we wanted to build early bindings for.

This is great stuff, it’s efficient because it creates early bound data only need the early bound entities you use in the code.  Limiting the entities you create the early bound entities file will save you time creating/refreshing the entities file and reduce the size of plugin dll’s.

Missing References

I added in my entity, ran the crmsvcutil.exe but then suddenly I got loads of errors.  A previous developer had created the entities file but hadn’t updated the EntitiesToBuild so I was missing a bunch of entities which used early binding.

I added these entities in and then I got some error with fields missing.

One of the plugins was no longer being used and many of the fields it was using had been deleted.


Finally it compiled and I was up and running again, I had forgotten what I was actually doing.


Early Bound Generator

The solution for creating the early bound classes worked, there is now a tool which can do it for you, so you don’t have to spend any time using the crmsvcutil with the command line.

The tool is the Early Bound Generator and has a nice GUI interface for you, I have reviewed it on a previous blog/video

here is a link to the codeplex site


The tool has been  improved since my initial review.  I will also proudly add the Hosk CRM blog is the link which brings the most traffic to the codeplex site and mentioning it here may even send a bit more traffic towards over that way, not to mention I love CRM tools.

If you want to see the other CRM tools I have reviewed click the link below


Why should I care about this error

It’s true you probably won’t get the error in the same scenario as above but it’s useful to know about this casting error and the cause.

If you ever see errors about casting Microsoft.Xrm.Sdk.Entity type to a custom entity type then you know there is some problem with the entities file.

Often the problem is the entities file is not up to date/not the latest version as I discussed in the blog post below earlier this week

Error – the source file is different from when the module was built

So as soon as you see this error, you know it’s an early bound/Entities problem.

One thought on “CRM 2011/2013 – System.InvalidCastException: Unable to cast object of type ‘Microsoft.Xrm.Sdk.Entity’ to type

  1. Stan July 15, 2015 / 3:17 pm

    Our “Invalid Cast Exception” after merging dlls is fixed by casting with .ToEntity();


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s