LINQ to SQL in Silverlight 3

In this article we would see how can we use Linq to Sql ORM in Silverlight 3 Application for interactinig with SQL Server Database.


Introduction

In this article we would see how can we use Linq to Sql ORM in Silverlight 3 Application for interactinig with SQL Server Database.

Creating Silverlight Project

Fire up Visual Studio 2008 and create a new Silverlight 3 Project. Name it as LINQ2SQLSL3.

LinqToSQLSilverlight1.gif

Now that you have created the Silverlight 3 Application, we would add a LINQ to SQL file that is *.dbml .

LinqToSQLSilverlight2.gif

For your information, I have created a Database named "EmployeeDB" with a table "EMP_BASIC_INFO" with the following details.

LinqToSQLSilverlight3.gif

Now, connect to the SQL Server from Server Explorer as shown in below figure.

LinqToSQLSilverlight4.gif

Drag and Drop the above above displayed table to the Object Relational Designer for Linq to SQL.

LinqToSQLSilverlight5.gif

Now we would change the above names to be user friendly.

LinqToSQLSilverlight6.gif

To interact with LINQ to SQL we need to have a service that client can call at any time.

Add Silverlight enabled WCF Service to the Web Project.

LinqToSQLSilverlight7.gif

In the Service.svc.cs add methods as per your requirement.

I have written two methods such as:

LinqToSQLSilverlight8.gif

And

LinqToSQLSilverlight9.gif

After writing the service build the project and get this service's reference in Silverlight 3 Project as shown in below figure.

LinqToSQLSilverlight10.gif

After you add the service it would create the ServiceReferences.ClientConfig file.

Now it's time to design our Silverlight UI in Blend, I have gone for a simple approach, where simple buttons and textbox would help us getting the result which would be displayed in DataGrid.

LinqToSQLSilverlight11.gif

The following XAML is for your reference:

LinqToSQLSilverlight12.gif

Now we would write client side code to call the service and display the result.

Following code is for Show All Button Click and displaying the result.

LinqToSQLSilverlight13.gif

Following code is for Show the text typed in txtSearch and based on that the result would be displayed.

LinqToSQLSilverlight14.gif

I guess that's it. Now we can test our application.

LinqToSQLSilverlight15.gif

When some text is typed and Search Button is clicked all the Employee whose name starts with the given text would be displayed.

LinqToSQLSilverlight16.gif

Hope this article helps.