2

In a WCF service, I have a situation where there is a datacontract (object) that contains a collection of child items (where the collection has a datamemeber attribute). The objects in the child collection have a reference to the parent as a property. If the parent object child collection is empty or contains a null parent reference, all is good, but if the parent reference is populated and parent children are populated, it serializes for ever.

Here's a set of test console code to show you what I'm talking about.

class Program
    {
        static void Main(string[] args)
        {

            MyParentObject parent = BuildParent();

            string xml = Serializer<MyParentObject>.Serialize(parent);

            System.Console.Write(xml);

            System.Console.ReadKey();

        }

        static MyParentObject BuildParent()
        {

            MyParentObject parent = new MyParentObject();
            parent.MyParentObjectId = 123;
            parent.MyParentObjectName = "Test Parent Object";
            parent.MyChildren = new List<MyChildObject>();

            for (int i = 0; i < 10; i++)
            {
                MyChildObject child = new MyChildObject();
                child.MyParent = parent;
                child.MyChildObjectId = i;
                child.MyChildObjectName = string.Format("Test Child Name {0}", i.ToString());
                parent.MyChildren.Add(child);
            }

            return parent;

        }

    }


    [DataContract]
    public class MyParentObject
    {

        [DataMember]
        public int MyParentObjectId { get; set; }

        [DataMember]
        public string MyParentObjectName { get; set; }

        [DataMember]
        public List<MyChildObject> MyChildren { get; set; }

    }

    [DataContract]
    public class MyChildObject
    {
        [DataMember]
        public MyParentObject MyParent { get; set; }

        [DataMember]
        public int MyChildObjectId { get; set; }

        [DataMember]
        public string MyChildObjectName { get; set; }

    }

public class Serializer<T>
    {

        public static string Serialize(T entity)
        {

            StringBuilder sb = new StringBuilder();


            DataContractSerializer dcs = new DataContractSerializer(typeof(T));

            using (XmlWriter writer = XmlWriter.Create(sb))
            {

                dcs.WriteObject(writer, entity);
                writer.Flush();
            }

            return sb.ToString();
        }

    }

Other than clearing out child/parent references that cause this infinite serialization loop, are there any ways around this?

EDIT: I know I can just remove the datamember attribute, but I'd like to keep it, and simply not serialize infinitely.

4

1 回答 1

4

尝试在 DataContract 属性中使用 IsReference 属性

[DataContract(IsReference = true)] 
于 2013-01-04T17:08:31.330 回答