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

        /// <summary>
        /// using Newtonsoft.Json;
        ///   [JsonIgnore]作用是取消属性的序列化,避免循环引用的的异常
        /// </summary>
        [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; }
        /*Timestamp时间戳,用于实现乐观并发,数据库自动生成无需赋值
        [Timestamp]
        public byte[] RowVersion { get; set; }
        */
        #region 多对多导航
        //多的一端
        /// <summary>
        /// 人员角色表,对人员角色来说,角色是多
        /// </summary>
        public virtual ICollection<PersonRole> PersonRoles { get; set; }
        #endregion
    }
public class Person
    {
        //[ScaffoldColumn(false)]
        //数据验证
        [BindNever] //解除模型绑定,防止传递来的模型数据修改此值
        [Key]
        public String Id { get; set; }
/*其他代码*/

        public virtual ICollection<PersonRole> PersonRoles { get; set; }

    }

执行结果:

<form id="form_@i" method="post" asp-area="Admin">
      <input type="text" name="PersonId" value="@Model[i].PersonId" />
      <input type="text" name="PersonName" value="@Model[i].GetPeople.Name" />
      <input type="text" name="RoleId" value="@Model[i].RoleId" />
      <input type="text" name="RoleName" value="@Model[i].GetRoles.RoleName" />
      
      <button type="button" onclick="">删除</button>
      <button type="button" onclick="">更新</button>
</form>

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

猜你喜欢

转载自blog.csdn.net/weixin_43604220/article/details/124797807
今日推荐