DataContract serialization support for .NET 3.5 SP1 including KnownType attributes

Jan 6, 2010 at 7:57 PM
Edited Jan 6, 2010 at 7:59 PM

Hi Damien,

For a while I have been using L2ST4 to allow my LINQ To SQL-generated classes to support DataContract serialization.  But my colleague pointed out this MSDN article that suggests the LINQ to SQL designer already supports it:  I had previously read Rick Stahl's post on this topic at, which made no mention of DataContract serialization.  Eventually I stumbled on L2ST4 and noticed its feature list, so I assumed that Microsoft did not support this with LINQ to SQL out of the box.  Am I wrong?  What exactly is the difference between the DataContract serialization support in L2ST4 and plain Visual Studio 2008 SP1?

Jordan Rieger

Jan 7, 2010 at 5:46 PM

LINQ to SQL supports the basic DataContract serialization out of the box. This basic serialization had no mechanism to tell it which end of an association was the owner to prevent serialization getting stuck in a loop and so LINQ to SQL would only serialize one side of the relationship.

In .NET 3.5 SP1 DataContract was extended with the IsReference attribute that let you tell it which end got to serialize the others object and which was just a reference back.

LINQ to SQL's designer and SQLMetal tools have not been extended to support this as there was not enough resource to fully test that LINQ to SQL was happy with objects serialized and deserialized using this new "IsReference" mechanism hence where this an option to turn on "DataContract SP1" serialization within this templates to do just that.


Jan 7, 2010 at 6:51 PM

Thanks for the information.  Can you elaborate on what you mean by LINQ to SQL only serializing one side of the relationship?  I assume this is related to the "Unidirectional" serialization setting in the designer.  But I ran some tests on an object with a one-to-many relationship, and the objects in the child collections appeared in serialized XML.  What more would be serialized if the IsReference attributes were turned on?  Would the objects in the child collection have a reference back to their parent, reflecting the normal LINQ relationships?  I think I've seen this type of reference in some serialized XML -- it uses a special "id" node/attribute added to the XML strictly for serialization/deserialization, right?

Jan 8, 2010 at 3:59 PM

Yes, you are seeing unidirectional serialization there. If your child objects had a reference back to the parent that would not have been represented in the XML because it would have caused the serializer to go round forever.

To avoid that happening SqlMetal doesn't put the serialization attribute on the other end. In .NET 3.5 they gave the IsReference attribute so it would know it should serialize the reference of the relationship but not the actual object it points to as that has been serialized elsewhere.


Jan 8, 2010 at 4:12 PM

Thanks, that makes sense.