【问题标题】:A circular reference was detected Linq检测到循环引用 Linq
【发布时间】:2013-03-22 00:53:27
【问题描述】:

在下方出现此错误 试图建立说 1 个帖子可以有多个 postComments 的关系

在序列化 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; }
    }   
}

【问题讨论】:

    标签: c# json asp.net-mvc-3 linq


    【解决方案1】:

    在您的Post 类中,您引用 PostComment 并且在您的 PostComment 类中您再次引用您的 Post,这是发生循环引用的地方,您可以使用 Json.NET http://james.newtonking.com/pages/json-net.aspx 并执行下面

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

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

    【讨论】:

    • 你有一个 sn-p 在序列化之前将其转换为匿名类。
    • var y = from p in db.Posts select new { PostID = p.PostID, Comments = p.Comments}
    • @cherhan 我可以把它放在我的所有应用程序中重用吗?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-11-10
      • 2016-02-15
      • 2014-02-05
      • 2015-07-14
      • 2021-07-04
      • 2021-09-01
      • 2017-04-26
      • 2017-03-21
      • 2016-12-15
      相关资源
      最近更新 更多