栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Self referencing loop detected for property异常

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Self referencing loop detected for property异常

在类之间存在互相调用的时,例如:有A,B两个类,A包含了B,B也包含了A时,在类序列化时和容易引发循环引用的异常。

 

这在关系映射中更为常见

解决方法:

 public class PersonRole
    {
        public String PersonId { get; set; }
        public String RoleId { get; set; }

        /// 
        /// using Newtonsoft.Json;
        ///   [JsonIgnore]作用是取消属性的序列化,避免循环引用的的异常
        /// 
        [JsonIgnore]
        public virtual Person GetPeople { get; set; }
        [JsonIgnore]
        public virtual Role GetRoles { get; set; }
    }

 我是使用[JsonIgnore]注释来解决的,他是Property级别,注意他所在的命名空间的引用为

using Newtonsoft.Json;
 public class Role
    {
        [BindNever]
        [Key]
        public string RoleId { get; set; }
        [Required(ErrorMessage = "角色名不能为空")]
        public string RoleName { get; set; }
        
        #region 多对多导航
        //多的一端
        /// 
        /// 人员角色表,对人员角色来说,角色是多
        /// 
        public virtual ICollection PersonRoles { get; set; }
        #endregion
    }
public class Person
    {
        //[ScaffoldColumn(false)]
        //数据验证
        [BindNever] //解除模型绑定,防止传递来的模型数据修改此值
        [Key]
        public String Id { get; set; }


        public virtual ICollection PersonRoles { get; set; }

    }

执行结果:

值得注意的是[JsonIgnore]注释仅需写在一段,写在主体或写在子体都可以。只在A或B中写[JsonIgnore]即可。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/895026.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号