Sunday, September 5, 2010

ASP.NET/MVC/Entity Framework Error "Unable to load type....required for deserialization."

Issue: Once you compile a change in your application and run it again you can receive this error, usually upon a post to a page:

Unable to load type System.Data.Entity.DynamicProxies.ClassName_A1398804A2AD2636A55B88C252D769E3468A12F2C5A773B1895C58D312108335 required for deserialization.

Or:

Unable to find assembly 'EntityFrameworkDynamicProxies-XXXX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.


What is happening here is that you are likely using POCO objects for the Entity Framework. These objects have proxy classes automatically generated for them behind the scenes. Upon a first visit to the application they are compiled, however if they are used in a post (for instance when posting data to an MVC Action) and that type is used in serialization then they have not yet been created.

Your code may look like:
[HttpPost]
public ActionResult Edit(Job job, [Deserialize] List someClasses)

When you post to this, the framework will NOT create the proxies automatically. You must access the page via a normal manner (ie via HttpGet) and the proxies will all be created. If you must have this feature, then you may possibly be able to do something in Application_Start to reference an Entity class and thus all of them should be auto generated.

In short - this fix is simply refresh the page. If posting to the page requires deserializing POCO objects from the page, then you will need to implement some mechanism to use the POCO Entities before the method is attempted, possibly in Application_Start.