2013-03-22 85 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

這意味着你必須在你對某些列數據庫中的一些約束必須參考有效在一些表格,並有這裏是一個循環引用。它必須按照彼此依賴的順序更新行,但由於循環引用,這是不可能的。沒有可以首先更新的單行,以滿足當時的數據庫限制。