ASP.NET MVC 5 在序列化 'Data.Item' 类型的对象时检测到循环引用

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

我的 ASP.NET MVC 项目出现循环引用错误

这是模型

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; }
}

这是获取 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);

我试过 db.Configuration.ProxyCreationEnabled = false; 但它不起作用。任何帮助将不胜感激。

在 global.asax 中将此代码用于全局 Json 序列化设置:

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

尝试用以下代码更改以下部分:

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

我遇到了同样的问题,我尝试了这个

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);