Entity Refs Not getting serialized with WCF service
In one of the project that I am working on, my client requires me to use WCF service to talk to Linq To SQL datacontext. The infrastructure guys would not open up port for me to access SQL server directly. Therefore I created a WCF project in my solution, added a reference to Business library and exposed my Linq to SQL entities using WCF service. By default you cannot expose your Linq to SQL entities, you have to mark SerializationMode on the datacontext to Unidirectional. Once you configure the datacontext for wcf serialization, the generated entities are marked with DataContract attribute and properties on the entity are marked with Datamember attribute. If Linq to SQL entity have child entities those also get serialized. However child entities do not get lazy loaded, you have to explicitly call LoadWith to immediately load child collections for them to be serialized. Here is a simply example that illustrates the behavior.
In the above screen shot, I am marking the serialization mode on the data context to Unidirectional which causes entity classes to be serialized using WCF service. In the above example, I also have a WCF service that exposes an operation called GetOrder. GetOrder method simply retrieves an order based on orderid passed. Since we want the OrderDetails to be also available on the client and serialized along with the Order, I am loading OrderDetails ahead of time.
In the above example, I am creating an instance of my wcf service and getting the order from the service. After retrieving the order, I am printing the orderid and the total of all the orderdetails for the order. But when I access the Customer property of the Order object I don't see any Customer property available, although my Linq to SQL entities had Customer property on my order object. For some reason, the Serialization mode does not take care of serializing entity refs.
I am still researching the problem. If anyone had seen this behavior and knows a workaround to the problem, please write a comment to let others know.