Skip to main content
 首页 » 编程设计

c#之检测到循环引用 Linq

2024年02月13日14xiaohuochai

下面出现这个错误 试图建立一个关系说 1 个帖子可以有多个 postComments

A circular reference was detected while serializing an object of type System.Collections.Generic.List`1[[DAO.Models.PostComment, DAO, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'.

int userId = (int)Session["UserId"]; 
try 
{ 
    IEnumerable<Post> userPosts; 
    userPosts = (from q in db.Posts 
                    where q.UserId == userId 
                    && q.PostId > postid 
                    select q).Take(5).ToList(); 
 
 
    return Json(userPosts.Select(x => new 
    { 
        success = 1, 
        contenttext = x.PostContent, 
        postId = x.PostId, 
        comments = x.PostComments 
    }), JsonRequestBehavior.AllowGet); 
 
} 
catch (Exception ex) 
{ 
    return Json(new { success = 0 }); 
 
} 
finally 
{ 
    //db.Dispose(); 
} 

我的帖子类

public partial class Post 
{ 
    public Post() 
    { 
        this.PostComments = new List<PostComment>(); 
    } 
 
    public int UserId { get; set; } 
    public int PostId { get; set; } 
    public string PostContent { get; set; }         
    public virtual ICollection<PostComment> PostComments { get; set; } 
 
    public partial class PostComment 
    { 
        public long PostCommentID { get; set; } 
        public int PostId { get; set; } 
        public int ParentCommentID { get; set; } 
        public System.DateTime CommentDate { get; set; } 
        public string Comment { get; set; } 
        public virtual Post Post { get; set; } 
    }    
} 

请您参考如下方法:

在您的 Post 类中,您引用了 PostComment,在您的 PostComment 类中,您再次引用了您的 Post,这就是通告的位置发生引用,您可以使用 Json.NET http://james.newtonking.com/pages/json-net.aspx并执行以下操作

JsonConvert.SerializeObject(myObject, Formatting.Indented,  
                            new JsonSerializerSettings {  
                                   ReferenceLoopHandling = ReferenceLoopHandling.Ignore  
                            }) 

要忽略引用循环处理,或者在序列化之前将其转换为匿名类。