I have order and orderproducts entites.
I then have the following 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; }
}
and 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>();
}
}
}
I am using the following action to return JSON...
public IQueryable<orders> Getorders()
{
IQueryable<orders> o = db.orders;
return o;
}
I get the error "The 'ObjectContent`1' type failed to serialize the response body for content type"
I've added the following to my global.asax...
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
If I remove the orderproducts entity from my viewmodel and data context, orders returns succesfully.
Any ideas on why the related entity is causing the serialization issue?
Try disabling the lazyload and if you dont want to disable the lazyload instead of returning entities from database create your own Model class to return the data.