2013-03-22 82 views
1

得到下面 此错误试图有关系,即表示1周后可以有多个postComments循环引用检测的LINQ

在序列化类型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(); 
} 

我Post类

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

回答

3

在你Post类,你参考PostComment并在PostComment你再次参考您的Post类,这是循环引用发生的地点,您可以使用Json.NET http://james.newtonking.com/pages/json-net.aspx,做下面的

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

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

+0

你有没有在将它串行化之前将它转换成匿名类的代码片段? – 2013-03-22 01:28:22

+0

var y =来自p中的db.Posts select new {PostID = p.PostID,Comments = p.Comments} – cherhan 2013-03-22 01:33:12

+0

你的问题解决了吗? – cherhan 2013-03-25 12:02:14

0

这意味着你必须在你对某些列数据库中的一些约束必须参考有效在一些表格,并有这里是一个循环引用。它必须按照彼此依赖的顺序更新行,但由于循环引用,这是不可能的。没有可以首先更新的单行,以满足当时的数据库限制。