Web API throws Exception when serializing object with virtual objects

May 5, 2012 at 3:31 AM

I've run into an issue with the Web API portion of the EFMVC project when I attempt to do a GET or any other response where serialization occurs.  The error I'm receiving is:

You must write an attribute 'type'='object' after writing the attribute with local name '__type'.

Stack Trace:

[XmlException: You must write an attribute 'type'='object' after writing the attribute with local name '__type'.]
   System.Web.Http.WebHost.HttpControllerHandler.EndProcessRequest(IAsyncResult result) +52394
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +514
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +354

Looking into this issue I've found that this occurs when serializing an object that has virtual objects contained within it, such as:

public virtual ICollection<MediaItem> Images { get; set; }

I'm able to get around the issue if I transfer the data to another POCO class that does not have any virtual objects and return that through the API.  It has no problem serializing that, but I don't want to have to re-create my classes just for this purpose.

It seems that there has to be a solution or some sort of workaround for this, or somebody here may know of a solution?  Any thoughts?

Thanks in advance, and an awesome job on EFMVC!!

May 5, 2012 at 5:58 AM

Quick Update.  I found that if I set ProxyCreationEnabled to false for the DataContext in RepositoryBase, this fixes the issue:

protected RepositoryBase(IDatabaseFactory databaseFactory)
{
	DatabaseFactory = databaseFactory;
	DataContext.Configuration.ProxyCreationEnabled = false;
	dbset = DataContext.Set<T>();
}

Will this cause problems elsewhere in the application or is this the correct route/location to disable this?

Feb 22, 2013 at 8:41 PM
Hi Hooked,

This does cause an issue with lazyloading in the Web project. Did you find a workaround?

Thanks,
Jason