我有订单和订单产品。
然后我有以下viewmodel ...
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; }
}
和db context ...
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>();
}
}
}
我正在使用以下操作返回JSON ...
public IQueryable<orders> Getorders()
{
IQueryable<orders> o = db.orders;
return o;
}
我收到错误“'ObjectContent`1'类型无法序列化内容类型的响应正文”
我已将以下内容添加到我的global.asax ...
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
如果我从viewmodel和数据上下文中删除orderproducts实体,则订单会成功返回。
关于相关实体为何导致序列化问题的任何想法?
答案 0 :(得分:1)
尝试禁用lazyload,如果您不想禁用lazyload而不是从数据库返回实体,请创建自己的Model类以返回数据。