我最初问过这个问题: 如何解决“指定的包含路径无效”?已回答,并且我的 .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 Products 上的设置器设为私有(如此处建议:http ://forums.asp.net/t/1773164.aspx/1 ),这可以清除错误,但我的产品不是返回 JSON。
我需要做什么才能使数据与其中的类别及其产品序列化?
编辑 这是我得到的堆栈跟踪:
[SerializationException: Object graph for type 'System.Collections.Generic.List`1[[Test.Models.Product, Test.Models, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' 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& completedSynchronously) +178