02 April, 2010

WCF: Prevent circular reference problems

Having a collection that contains elements pointing back to their parents, you are almost certain to run into a serialization problem.

image

The problem is, that the child points back to it’s parent. Both child and parent carries a collection of children and the serializer runs into an infinite loop of elements => you have a serialization problem!

image

This was previously solved by a custom serializer, but now (3.5 SP1/3.0 SP2) you can cope the problem by adding the attribute ‘IsReference’ to the datacontract of the type in question (see above). This prevents the endless looping and marks the (in the above case) folder as a reference only. In this way -  the ‘Parent’ folder object is only stored as a reference and NOT a full ‘folder’ object.

No comments: