ef-code-first – 在WebAPI Controller中序列化EF Code First 5.0数据时出错

我原来问过这个问题:
已经回答了 How Do I Resolve “A specified Include path is not valid”?,而我的.Include()现在正在工作,但是,当序列化程序试图使它变得神奇时,我收到以下错误
You must write an attribute 'type'='object' after writing the attribute 
with local name '__type'.

这是我正在做的返回数据:

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

我的类定义相当简单:

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; }
}

我也尝试删除’虚拟’,但后来我得到循环引用.我尝试将ICollection产品上的setter设置为私有(如此处建议:http://forums.asp.net/t/1773164.aspx/1),这样可以清除错误,但之后我的产品不是返回的JSON的一部分.

我需要做些什么来使数据与类别及其产品序列化?

编辑
这是我得到的堆栈跟踪:

[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

解决方法

为了解决这个问题,我需要:

>禁用延迟加载,和
>使用System.Runtime.Serialization中的IgnoreDataMember作为类别导航属性(Product类的后引用)上的属性.

希望这有助于某人.

为了解决XML-ish错误,我在这里使用了帮助:
http://www.strathweb.com/2012/03/serializing-entity-framework-objects-to-json-in-asp-net-web-api/

为了解决循环引用的问题,我以此为指导:
MVC 4,Upshot entities cyclic references

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...