zoukankan      html  css  js  c++  java
  • 序列化类型 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来实现。

  • 相关阅读:
    Xposed模块开发基本方法记录
    Win8.1下运行环境/配置问题解决方案总结
    wordpress安装记录
    编译时:virtual memory exhausted: Cannot allocate memory
    Support for AMD usage of jwplayer (require js)
    UC 浏览器远程调试手机web网页记录
    手机浏览器页面点击不跳转(Android手机部分浏览器) 浏览器双击放大网页 解决
    aes 加密,解密(2)
    aes 加密,解密
    ionic 安装步骤
  • 原文地址:https://www.cnblogs.com/guolihao/p/3214139.html
Copyright © 2011-2022 走看看