【问题标题】:ASP.NET MVC 5 A circular reference was detected while serializing an object of type 'Data.Item'ASP.NET MVC 5 在序列化“Data.Item”类型的对象时检测到循环引用
【发布时间】:2020-04-27 14:20:54
【问题描述】:

我的 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;,但它不起作用。任何帮助将不胜感激。

【问题讨论】:

    标签: c# json asp.net-mvc asp.net-mvc-5


    【解决方案1】:

    我遇到了同样的问题,我试过了

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我收到此错误 '''Newtonsoft.Json.JsonSerializationException: '自引用循环检测到类型为 'Data.Item'。路径“[0].AspNetUser.Items”。 ''' imgur.com/c9nWVq4
      猜你喜欢
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多