我如何解决Json序列化循环引用错误? [英] How did I solve the Json serializing circular reference error?

查看:377
本文介绍了我如何解决Json序列化循环引用错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

发布了此处请求通过EF4 CTP5返回序列化对象时如何解决循环引用错误。我遇到了一个WCF Web表单项目的同样的问题。



我能够在我的WCF / Web表单项目和我的MVC3项目。我不认为这是什么类型的项目,因为这似乎是一个EF序列化的事情。



我解决了这个问题,通过禁用我的ObjectContext构造函数中的ProxyCreation,如这个:

  public class MyObjectContext:DbContext,IDbContext 
{
public MyObjectContext(string connectionStringName):base (connectionStringName)
{
((IObjectContextAdapter)this).ObjectContext.ContextOptions.ProxyCreationEnabled = false;
}
public DbSet< Product>产品{get; set;}
//等。
}

我的问题是:有人可以解释为什么看起来会解决问题吗? / p>

我认为这个问题与我的POCO的导航属性有关,但之后我被困了。谢谢。

解决方案

如果你关闭代理创建,你也会关闭延迟加载。当实体的序列化时,它访问所有导航属性。如果启用了延迟加载,它将加载所有相关对象,并尝试将其序列化。再次访问所有属性,包括指向父对象的导航属性。此时,您必须说序列化,这个属性是循环引用,或者它会再次序列化对象,并以无限循环继续。



这里的诀窍可能是使用 ScriptIgnore 属性注释子实体中的循环导航属性。


There is post here that asks how to solve the circular reference error when returning a serialized object via EF4 CTP5. I ran into this same problem with a WCF web forms project a while back.

I was able to "solve" this problem in my WCF/web forms project and in my MVC3 project. I don't think it matters what type of project as this appears to be a EF serialization "thing".

I solved the problem by disabling ProxyCreation in my ObjectContext constructor like this:

public class MyObjectContext : DbContext, IDbContext
{
     public MyObjectContext(string connectionStringName) : base(connectionStringName)
     {
        ((IObjectContextAdapter)this).ObjectContext.ContextOptions.ProxyCreationEnabled = false;
     }
     public DbSet<Product> Products {get;set;}
     //etc.
} 

My question is: Could someone explain why this would seemingly solve the problem?

I think the problem has to do with navigation properties in my POCO's but after that I am stumped. Thanks.

解决方案

If you turn off proxy creation you also turn off lazy loading. When serialization of entity occures it visits all navigation properties. If lazy loading is enabled it loads all related objects and tries to serialize them as well. Again it visits all their properties including navigation properties pointing back to parent object. At this point you have to say serialization that this property is circular reference or it will serialize the object again and continue in infinite loop.

The trick here could be to annotate your circular navigation property in child entity with the ScriptIgnore attribute.

这篇关于我如何解决Json序列化循环引用错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆