Circular reference using JsonSerializer

Nov 22, 2011 at 8:53 AM
Edited Nov 23, 2011 at 3:52 AM


Getting the following while using WebMethods that serialize an Entity collection:  

System.InvalidOperationException: A circular reference was detected while serializing an object of type '[Entity Framework EntityType]'.
   at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)

I think I have it narrowed down to "A -> B -> A" relationship circular references generated by the EF T4 Toolbox template.  To fix this, you need to add the [ScriptIgnore] attribute decoration to those properties you don't want serialized.  From what I can see, it seems to be navigation properties that cause this issue. 

For instance:

public class Order
{
     public int Id { get; set; }
     public User Customer { get; set; }
 
     [ScriptIgnore]
     public List<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
     public int Id { get; set; }
     public string Name { get; set; }
     public decimal Price { get; set; }

     [ScriptIgnore]
     public Order Order { get; set; }
}