Error serializing EF Code First 5.0 data in WebAPI Controller

I originally asked this question: How do I resolve it? The specified Include path is invalid "? , Which was answered, and my .Include () now works, however, when the serializer tries to work with magic, I get the following error:

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

Here is what I do to get the data back:

 var everything = dc.Categories .Include(c => c.Products); 

My class definitions are pretty simple:

 public class Category { public int CategoryId { get; set; } public string Title { get; set; } public virtual ICollection<Product> Products { get; set; } } public class Product { public int ProductId { get; set; } public string Title { get; set; } public virtual Category Category { get; set; } } public class ProductDataContext : DbContext { public DbSet<Category> Categories { get; set; } public DbSet<Product> Products { get; set; } } 

I also tried removing "virtual", but then I get circular links. I tried to make the setter on ICollection Products private (as suggested here: http://forums.asp.net/t/1773164.aspx/1 ), which gets an error to clear, but then my products are not part of the returned JSON.

What do I need to do to get serialization data with categories and their products inside?

EDIT Here was the stack trace I was getting:

 [SerializationException: Object graph for type &#39;System.Collections.Generic.List`1[[Test.Models.Product, Test.Models, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]&#39; contains cycles and cannot be serialized if reference tracking is disabled.] System.Web.Http.WebHost.HttpControllerHandler.EndProcessRequest(IAsyncResult result) +30206 System.Web.Http.WebHost.HttpControllerHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +10 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9478661 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +178 
+7
asp.net-web-api entity-framework-5 ef-code-first
source share
1 answer

To fix this I need:

  • Disable lazy loading and
  • Use the IgnoreDataMember from System.Runtime.Serialization as an attribute of the Category navigation property ( IgnoreDataMember in the Product class).

Hope this helps someone.

To get around XML-ish errors, I used help here: http://www.strathweb.com/2012/03/serializing-entity-framework-objects-to-json-in-asp-net-web-api/

To get around the problem with circular references, I used this as a guide: MVC 4, circular references to remote objects

+13
source share

All Articles