Using Linq To SQL With WCF Service
The other day I met someone in the usergroup who asked me if I know how to use Linq to SQL classes in wcf and if Linq to SQL classes were serializable over the wire. I haven't done any wcf except attended quite a few talks on WCF. I decided to research of what I need to do to consume my Linq to SQL classes using wcf service with asp.net as a presentation layer. Here is a small walk through that illustrates an example of that. I am going to be demonstrating the example using Customer class from NorthWind database.
Add a new class library project and call it NorthWind.Business as shown below.
Then I added a WCF service project and called it NorthWindService as shown below.
Then add a asp.net 3.5 website project to the solution. The solution explorer looks something like this.
On the class library project, I will add a NorthWind Linq to SQL file and drag customer object on the designer. In order to ensure my entities are serializable, I will change the Serialization Mode to Unidirectional by right clicking anywhere on the OR designer and going to its properties as shown below.
When you set the serialization mode to Unidirectional, the class generated by visual studio gets attributed with DataContract and properties get attributed with DataMember.This makes the class be easily consumed by WCF service.
I am also going to expose a static method on my customer entity called GetCustomersByCity which will retrieve all the customers for city passed in as a parameter. In order to accomplish that, I will add a partial class called Customer in my NorthWind.Business class library project as shown below.
Now that I am done with my business library, I will go ahead and add a reference to my library in WCF service project. Once that's done I will modify my service interface and it implementation as follows.
My service implementation is as follows
In the service implementation, I have 3 methods. In GetCustomersByCity I am calling the static method GetCustomersByCity in my partial customer class. On InsertCustomer, I am sending the customer object to my NorthWind datacontext. UpdateCustomer is a bit tricky. I am first attaching my customer to NorthWind datacontext. This is important because serialized customer object passed in as a parameter is detached from the datacontext. Therefore datacontext is not aware of what to do with the object. This why I am passing my modified customer object as the first parameter. Passing true in the second parameter tells the datacontext that customer object passed in is to be considered in a modified state and to use optimistic concurrency based on the timestamp column defined on my customer table. After notifying datacontext of the customer object I am calling submitchanges to persist the object to the database.
Once I have the WCF service configured I can simply add service reference to my asp.net application and create a new instance of the proxy object to consume the service.