When classes call each other, for example: there are two classes A and B, A contains B, and B also contains A, it is easy to cause a circular reference exception during class serialization.
This is more common in relational mapping
Solution:
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; }
}
I solved it using the [JsonIgnore] annotation, which is at the Property level. Note that the reference to the namespace where it is located is
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; }
}
Results of the:
<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>
It is worth noting that the [JsonIgnore] annotation only needs to be written in one paragraph, either in the main body or in the sub-body. Just write [JsonIgnore] in A or B.