Welcome to Microsoft .NET Framework 3.0 Community (NetFx3)

The .NET Framework is Microsoft's managed code programming model for building applications that have visually stunning user experiences, seamless and secure communication, and the ability to model a range of business processes.

Learn More...

WCF Community Bloggers

Wednesday, May 14, 2008 - Posts

  • DataContracts and object references

    Another new WCF feature that's part of .NET 3.5 SP1 has to do with better support for object references. DataContractSerializer has always supported serializing object references and dealing with graphs, including cycles, and not just simple trees. But doing so is not the default behavior -- you have to tell DataContractSerializer that you want it to preserve object references when you instantiate it. Let's look at a simple example. Supposed that you have the following cyclic object graph (I'm assuming the same Person type that I used in my previous post ): Person p = new Person (); p.Id = "123" ; p.Name = "Aaron" ; p.Spouse = new Person (); p.Spouse.Id = "456" ; p.Spouse.Name = "Monica" ; p.Spouse.Spouse = p; ... And now let's supposed that you want to serialize it. If you create the DataContractSerializer using the default constructor, it will throw an exception when it identifies the cycle during serialization. However, you can tell DataContractSerializer to preserve object references using one of the other constructors: DataContractSerializer dcs = new DataContractSerializer ( typeof ( Person ), null , int .MaxValue, false , true /* preserve object refs */ , null ); using ( FileStream fs = new FileStream ( "person.xml" , FileMode .Create)) { dcs.WriteObject(fs, p); } The resulting person.xml file now looks like this: < Person z:Id = " 1 " xmlns = " http://schemas.datacontract.org/2004/07/SerializationSp1 " xmlns:i = " http://www.w3.org/2001/XMLSchema-instance " xmlns:z Read More...

Copyright © 2007 Microsoft Corporation. All Rights Reserved. | Terms of Use | Privacy Statement | Contact Us