How To Pass LINQ To SQL Data Over WCF
In scenarios where there is a need to retrieve data from a remote service, a programmer is usually faced with an additional task of manually defining a data structure (e.g. a class) that would hold the information returned. For example, data stored in a database table may be retrieved using either data reader or a data adapter and placed in a collection of custom objects, or even a DataSet.
With WCF, an object returned from a service must be serializable. In addition, it should use the new [DataContract] style serialization optimized for WCF, instead of the old fashioned [Serializable] one.
With Visual Studio 2008, the task of creating data structures ready for WCF serialization has been simplified greatly.
Let’s assume we have a User table in our database with a list of users and their information. We will need to add a Link To SQL data class file to our WCF Service project in our Visual Studio solution:
Once the design surface screen comes up, drag User table from Server Explorer onto it to create a class.
Hit “Save” button. Visual Studio automatically creates a corresponding User class ready to be used in your application. However by default the class is not marked with [DataContract] attribute and therefore cannot be used with WCF. To change this setting, first click your mouse on an empty space on the design surface and then adjust the Serialization Mode value in Properties grid from None to Unidirectional.
That’s it. Now you can create a WCF method to retrieve information and return it to a WCF client. Here is an example of such code:
public IList<User> GetUsers()
{
MyDatabaseDataClassesDataContext db = new MyDatabaseDataClassesDataContext();
var result = from u in db.Users
select u;
return result.ToList();
}

