Serializing a Data Class (LINQ2SQL) for WCF


I created a class that implements a service contract interface so that I can return an array of data from a WCF service back to the client application.

The exposed method in the class return’s an array of Data Classes (an array of records from a database table) generated by the MSLINQ2SQL generator.

When generating the client code from the WCF service, an exception was raised stating
That the class could not be serialized.

Service cannot be started. System.Runtime.Serialization.InvalidDataContractException: Type ‘TDC_LIB.OM.TMPPlan’ cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.DataContract.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
at System.Runtime.Serialization.DataContract.GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
at System.Runtime.Serialization.DataContract.GetDataContr…

Make sure that your data context object has the property “Serialization Mode” set to Unidirectional. This will add DataContract/DataMember attributes to the associated fields in your data classes.