序列化类型 System.Data.Entity.DynamicProxies 的对象时检测到循环引用

        学习 EF Code First+MVC 时遇到了在请求JsonResult时出现 序列化类型 System.Data.Entity.DynamicProxies 的对象时检测到循环引用 的异常,原因是实体之间有关联关系,在序列化这些相关的

数据对象的时候,产生无限循环引用的现象。

       Example:

    public class CollegeInfoModel
    {
        public Guid CollegeId { get; set; }
        [Display(Name = "学院")]
        public string CollegeName { get; set; }
        [JsonIgnore]
        public virtual List<DepartmentInfoModel> Departments { get; set; }
    }

    public class DepartmentInfoModel
    {
        public Guid DepartmentId { get; set; }
        public string DepartmentName { get; set; }
        public virtual CollegeInfoModel CollegeInfoObj { get; set; }
        [JsonIgnore]
        public virtual List<ClassInfoModel> Classinfos { get; set; }
    }

CollegeInfoModel中有List<DepartmentInfoModel>,DepartmentInfoModel中有CollegeInfoModel。

1.最简单的解决方案:获取需要的字段

from c in stuCtx.CollegeInfoes where c.CollegeId == collegeId select new { c.CollegeId, c.CollegeName };

2.可以尝试删除所有的导航属性的virtual关键字禁用延迟加载和创建代理,然后使用预先加载,而不是显式地加载所需的对象图

3.没有必要删除virtual关键字导航性能(这将使延迟加载的模型完全不可能)。这足以创建代理(以及禁用延迟加载)禁用代理扰乱序列一样:

Context.Configuration.ProxyCreationEnabled = false;

以上3种方案可以看  Xia.CJ 的博客。 参考

我的解决方案是自定义JsonResult来实现。

原文地址:https://www.cnblogs.com/guolihao/p/3214139.html