Search code examples
wcfentity-frameworkserializationentity-framework-4poco

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:

[ServiceContract]
[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="http://schemas.datacontract.org/2004/07/LmApi" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Body>Test message</Body>
    <Group z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"/>
</Message>

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


Solution

  • 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)