Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

entity framework - How did I solve the Json serializing circular reference error?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...