Solve a circular reference in WCF from my POCOs

I have a couple of classes (for now) and I'm trying to clear up a circular reference between the two since it is killing WCF's serialization.

I am using EF with POCOs in a WCF REST service is that helps. I have simplified my problem down to bare bones for an easy example here:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Groups
    [WebGet(UriTemplate = "")]
    public Message GetCollection()
        var message = new Message { Body = "Test message" };
        var group = new Group { Title = "Title of group" };
        message.Group = group;
        group.Messages = new List<Message> { message };
        return message;

public class Message
    public string Body { get; set; }
    public Group Group { get; set; }

[DataContract(IsReference = true)]
public class Group
    public string Title { get; set; }
    public ICollection<Message> Messages { get; set; }

I have added the [DataContract(IsReference = true)] to the Group class so that the circular reference is cleaned up however my returned results end up like this:

<Message xmlns="" xmlns:i="">
    <Body>Test message</Body>
    <Group z:Id="i1" xmlns:z=""/>

Where are the properties of the Group and how can I get them?



There are no properties associated with Group. That's why all you see is the ID of 1.

The reason is that as soon as you annotate the Group class with [DataContract(IsReference = true)], you are telling the DataContract serializer that it's no longer a POCO type. It's a DataContract type.

So, to serialize Group with properties, you now need to go ahead and annotate the Title and Message properties with DataMemberAttribute.

An alternative would be use the "preserveObjectReferences", which you can pass as a parameter to DataContractSerializer, DataContractSerializerOperationBehavior, and other classes.

Hope this helps!

I decided to make my own smaller classes that have a constructor that takes an entity and sets all of this lighterweight properties correctly.

Basically it is a very small copy of the class that has just the properties needed in the payload. (Obviously I have excluded the problem navigation properties)

Need Your Help

Set file permissions for mysqldump output

ubuntu-12.04 crontab mysqldump chmod

I have a daily backup made that goes into my Dropbox folder. The file won't sync to could because of its default permission.


objective-c ios compiler-construction exc-bad-access llvm-gcc

Below code runs just fine on GCC 4.2 but fails with EXC_BAD_ACCESS in LLVM GCC 4.2