Web API 2 个相关实体

Web API 2 related entities

我有订单和订单产品实体。

然后我有以下视图模型...

public class orders
{
    [Key]
    public int orderid { get; set; }
    public int userid { get; set; }
    public System.DateTime createdate { get; set; }
    public string orderstatus { get; set; }

    public virtual ICollection<orderproduct> orderproducts { get; set; }
}

public class orderproducts
{
    [Key]
    public int orderproductid { get; set; }
    public int productid { get; set; }
    public int orderid { get; set; }

    public virtual order order { get; set; }
    public virtual product product { get; set; }
}

和数据库上下文...

namespace salesWebTest.DAL
{
public class nviewContext : DbContext
{
public nviewContext() : base()
    {
        Configuration.LazyLoadingEnabled = true;
    }

    public nviewContext(string Connection) : base(Connection)
    {
        Configuration.LazyLoadingEnabled = true;
    }


    public DbSet<salesWebTest.viewModel.orders> orders { get; set; }
    public DbSet<salesWebTest.viewModel.orderproducts> orderproducts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}
} 

我正在使用以下操作 return JSON...

public IQueryable<orders> Getorders()
    {
        IQueryable<orders> o = db.orders;
        return o;
    }

我收到错误 "The 'ObjectContent`1' type failed to serialize the response body for content type"

我已将以下内容添加到我的 global.asax...

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

如果我从我的视图模型和数据上下文中删除 orderproducts 实体,订单 return 会成功。

关于为什么相关实体导致序列化问题有任何想法吗?

尝试禁用惰性加载,如果您不想禁用惰性加载而不是 returning 数据库中的实体,请创建您自己的模型 class 到 return 数据。