How to consume ADO.NET Data Services in Silverlight 3

This article has been archived. It is offered "as is" and will no longer be updated.
This article describes an All-In-One Code Framework sample that is available for download.

You can consume Microsoft ADO.NET Data Services in Microsoft Silverlight 3. You can send query, update, delete, or insert request to ADO.NET Data Services, which access databases on your behalf. This article contains step-by-step instructions for querying data by using Silverlight 3 together with ADO.NET Data Services. Other instructions, such as how to perform an update operation, can be found in the sample.

Difficulty level

Download information

To download this code sample, click the following link:


Technical overview

Before you follow the instructions, make sure that you have deployed the CSADONETDataService project or the VBADONETDataService project. Also, make sure that the Web page that hosts the Silverlight application is in the same domain of ADO.NET Data Services. If not, use a cross domain policy file for the domain of ADO.NET Data Services. For example, the following are the URI of the page that hosts Silverlight and the URI of your ADO.NET Data Services, respectively:
  • http://domain:1234/TestPage.aspx
  • http://domain:1235/SchoolLinqToEntities.svc
In this example, you must make sure that the client can access the cross domain policy file by using one of the following:
  • http://domain:1235/clientaccesspolicy.xml
  • http://domain:1235/crossdomain.xml

To add the ADO.NET Data Services client proxy class, follow these steps:
  1. Create a Silverlight 3 project in Visual Studio.
  2. Right-click the project node in the Solution Explorer window, and then click Add Service Reference.
  3. Input the URI of ADO.NET Data Services in the Address text box, and then click Go next to the text box.
  4. In the Services panel, you will see the displayed service.
  5. Click OK.
  6. Click the Show All Files icon in the Solution Explorer window.
  7. Expand the Service References folder in the Solution Explorer window, you will see the service reference you just added. Then, expand all the descendent nodes of it.
  8. You will see a Reference.cs file or a Reference.vb file. Double-click it.
  9. You will find an automatically generated class that is derived from DataServiceContext. In addition, you can get an automatically generated class that represents the model of database. You can use these classes to send REST requests to ADO.NET Data Services.
To use a proxy class to request ADO.NET Data Services, follow these steps:
  1. Create a UserControl class in the Silverlight project.
  2. Initialize necessary objects in the UserControl class:
    // The data source of DataGrid control        private List<ScoreCardForSchoolLinqToEntities> _collection = new List<ScoreCardForSchoolLinqToEntities>();        // The URL of ADO.NET Data Service        private const string _schoolLinqToEntitiesUri =           "http://localhost:8888/SchoolLinqToEntities.svc";        // _collection => returnedCourseGrade => _entities ={via async REST call}=> ADO.NET Data Serviceprivate SQLServer2005DBEntities _entities;
    Note In this code, SQLServer2005DBEntities is the class deriving from DataServiceContext that is generated in step a.
  3. Define your query and call the BeginExecute() method to send a sync REST call to ADO.NET Data Services. Additionally, hook up an event handler, which will fire when response from ADO.NET Data Services is received:
    private void LoadData()        {            _entities = new SQLServer2005DBEntities(new Uri(_schoolLinqToEntitiesUri));            DataServiceQuery<CourseGrade> query = (DataServiceQuery<CourseGrade>)(                from c in _entities.CourseGrade.Expand("Person").Expand("Course")                select c);            query.BeginExecute(OnCourseGradeQueryComplete, query);        }    private void OnCourseGradeQueryComplete(IAsyncResult result)        {            Dispatcher.BeginInvoke(() =>            {                DataServiceQuery<CourseGrade> query =                       result.AsyncState as DataServiceQuery<CourseGrade>;                try                {                    var returnedCourseGrade =                        query.EndExecute(result);                    if (returnedCourseGrade != null)                    {                        _collection = (from c in returnedCourseGrade.ToList()                                       select new ScoreCardForSchoolLinqToEntities()                                       {                                           // Due to the following QueryInterceptor at server side only Course ID>4000 can be returned:                                           // [QueryInterceptor("Course")]                                           // public Expression<Func<Course, bool>> QueryCourse()                                           // {                                           //     // LINQ lambda expression to filter the course objects                                           //     return c => c.CourseID > 4000;                                           // }                                           CourseGrade = c,                                           Course = c.Course == null ? "Only Course ID>4000 can be shown here" :                                               c.Course.Title,                                           Grade = c.Grade,                                           PersonName = string.Format("{0} {1}",                                           c.Person.FirstName, c.Person.LastName)                                       }).ToList();                        this.mainDataGrid.ItemsSource = _collection;                    }                }                catch (DataServiceQueryException ex)                {                    this.messageTextBlock.Text = string.Format("Error: {0} - {1}",                        ex.Response.StatusCode.ToString(), ex.Response.Error.Message);                }            });        }
    Note In the event handler, call the EndExecute() method to end the query, retrieve and store data into memory. In above code the call to the returnedCourseGrade.ToList() method returns all the data that is returned by the query.
  4. Add a DataGrid control in the XAML file of your UserControl to show data:
    <data:DataGrid x:Name="mainDataGrid"></data:DataGrid>
  5. Add a TextBlock to show exception message:
    <TextBlock x:Name="messageTextBlock"></TextBlock>
For more information about network security access restrictions in Silverlight, visit the following Microsoft Developer Network (MSDN) Web site:Note For more information about how to create and to deploy the sample application, refer to the Readme.txt file that is included in the download package.

Technology category

  • Silverlight, ADO.NET Data Services


This code sample contains the following programming languages:
LanguageProject Name
Visual C#CSADONETDataServiceSL3Client
Visual Basic .NETVBADONETDataServiceSL3Client



  • ADO.NET Data Services, Silverlight

What is All-In-One Code Framework?

All-In-One Code Framework shows most Microsoft development techniques by using code samples in different programming languages. Each example is carefully selected, composed, and documented to show one common code scenario. For more information about All-In-One Code Framework, visit the following Web site:

How to find more All-In-One Code Framework samples

To find more All-In-One Code Framework samples, you can search for kbcodefx together with related keywords on Or, you can simply click the following link:
For more information, visit the following Web site:
Rapid publishing disclaimer
Microsoft corporation and/or its respective suppliers make no representations about the suitability, reliability, or accuracy of the information and related graphics contained herein. All such information and related graphics are provided "as is" without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information and related graphics, including all implied warranties and conditions of merchantability, fitness for a particular purpose, workmanlike effort, title and non-infringement. You specifically agree that in no event shall Microsoft and/or its suppliers be liable for any direct, indirect, punitive, incidental, special, consequential damages or any damages whatsoever including, without limitation, damages for loss of use, data or profits, arising out of or in any way connected with the use of or inability to use the information and related graphics contained herein, whether based on contract, tort, negligence, strict liability or otherwise, even if Microsoft or any of its suppliers has been advised of the possibility of damages.

Article ID: 982499 - Last Review: 12/12/2015 04:16:28 - Revision: 1.0

Microsoft Visual Studio 2008 Service Pack 1

  • kbnosurvey kbarchive kbsurveynew kbinfo kbnomt kbrapidpub kbcodefx atdownload KB982499