c# – Json在序列化类型对象时检测到循环引用

给班:

public class Parent
{
    public int id {get; set;}
    public int name {get; set;}

    public virtual ICollection<Child> children {get; set;}
}

[Table("Child")]
public partial class Child
{
    [Key]
    public int id {get; set;}
    public string name { get; set; }

    [NotMapped]
    public string nickName { get; set; }
}

控制器代码:

List<Parent> parents = parentRepository.Get();
return Json(parents); 

它适用于LOCALHOST,但在实时服务器上不起作用:

ERROR : Json A circular reference was detected while serializing an object of type

我做了一个搜索,找到了[ScriptIgnore]属性,所以我改变了模型

using System.Web.Script.Serialization;

public class Parent
{
    public int id {get; set;}
    public int name {get; set;}

    [ScriptIgnore]
    public virtual ICollection<Child> children {get; set;}
}

但实时服务器(win2008)也会发生同样的错误。

如何避免该错误并成功序列化父数据?

尝试以下代码:

return Json(
    parents.Select(x => new {
        id = x.id,
        name = x.name,
        children = x.children.Select(y => new {
            // Assigment of child fields
        })
    })); 

只有父属性:

return Json(
    parents.Select(x => new {
        id = x.id,
        name = x.name
    })); 

这不是真正的问题的解决方案,但它是一个常见的解决方法,当序列化DTO …

http://stackoverflow.com/questions/14592781/json-a-circular-reference-was-detected-while-serializing-an-object-of-type

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – Json在序列化类型对象时检测到循环引用