Romi
Romi

Reputation: 109

ASP.NET MVC 5 A circular reference was detected while serializing an object of type 'Data.Item'

I am getting a circular reference error in my ASP.NET MVC Project

Here is the Model

public partial class Item
{

    public Item()
    {
        this.Inventories = new HashSet<Inventory>();
        this.PurchasesDetails = new HashSet<PurchasesDetail>();
        this.SalesDetails = new HashSet<SalesDetail>();
    }

    public int Id { get; set; }
    public string Code { get; set; }
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public int MeasurementID { get; set; }
    public int Quantity { get; set; }
    public decimal BuyPrice { get; set; }
    public decimal SalePrice { get; set; }
    public decimal CommisionRate { get; set; }
    public Nullable<System.DateTime> MftDate { get; set; }
    public Nullable<System.DateTime> ExpDate { get; set; }
    public Nullable<int> StockLimit { get; set; }
    public string Description { get; set; }
    public string UserID { get; set; }
    public virtual AspNetUser AspNetUser { get; set; }
    public virtual Category Category { get; set; }
    public virtual ICollection<Inventory> Inventories { get; set; }
    public virtual Measurement Measurement { get; set; }
    public virtual ICollection<PurchasesDetail> PurchasesDetails { get; set; }
    public virtual ICollection<SalesDetail> SalesDetails { get; set; }
}

And Here is code to get the JSON

 db.Configuration.ProxyCreationEnabled = false;
        var items = db.Items.Include(i => i.AspNetUser).Include(i => i.Category).Include(i => i.Measurement).ToList();
        return Json(new { data = items }, JsonRequestBehavior.AllowGet);

I tried with db.Configuration.ProxyCreationEnabled = false; but it's not working. Any help would be highly appreciated.

Upvotes: 1

Views: 957

Answers (2)

Sanjay Kumar
Sanjay Kumar

Reputation: 345

I faced the same problem and I tried this

var plan_master = from s in db.Plan_Master select s;

        var plans = plan_master.Select(S => new
        {
            S.Plan_ID,
            S.Plan
        });

        return Json(new { data = plans }, JsonRequestBehavior.AllowGet);

Upvotes: 1

Nikunj Patel
Nikunj Patel

Reputation: 247

In global.asax put this code for global Json serialization settings :

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Try to change following section of code with below:

string json = JsonConvert.SerializeObject(items, Formatting.None);
    return Json(new { data = json }, JsonRequestBehavior.AllowGet);

Upvotes: 0

Related Questions