Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

January 31, 2011

Accessing Data in a Silverlight Application: EF

Filed under: ASP.NET RIA Services,C#,Silverlight,VB.NET @ 12:29 am

One of the challenges of building a Silverlight line of business (LOB) application is getting the data from the business database. The business database resides on a server computer and the Silverlight application resides on each user’s computer. This post covers using Entity Framework (EF) to get the data from the database server to the Silverlight application.

NOTE: This post is part of a series that starts with this prior post. The example in this post uses the application that is built as part of that series.

The primary choices for getting data into your Silverlight application are:

  • Build an entity class in the Silverlight application that is populated from a WCF service.
  • Generate an entity class in the Silverlight application using WCF RIA services and Entity Framework.
  • Generate an entity class in the Silverlight application using WCF RIA services and your business objects (sometimes called Plain Old CLR Objects or POCOs). See this prior post for more information on using WCF RIA with your business objects.

Plus there are third party products that provide similar functionality.

This post focuses on the second approach: using Entity Framework and WCF RIA Services.

Prerequisites

Before beginning, you need a database. I had two choices when preparing the example for this post:

1) Build a database with a single table for the student and scores. This option would keep things very simple and readily map to the class created in the prior posts of this series.

2) Build a database with several tables that more closely map to a "real" database design. Very rarely would a real LOB application access only a single table.

I picked option 2 in order to provide a more realistic example. So if you want to work through this example, build a database. I called mine InStepSM for InStep Student Management, which is the sample application built in this blog series. Then add three tables:

image

Enter some test data into each table. Be sure to match up the foreign keys.

Entity Framework

Once you have the database, you are ready to build the Entity Framework model.

1) Open the Web project of your Silverlight solution.

2) Add an ADO.NET Entity Data Model using the appropriate VB.NET or C# template.

image

3) Select to generate the data model from the database.

image

4) Select the connection to the desired database.

image

5) Select the desired tables, views, or stored procedures. In this example, all three tables are selected.

image

The result is an Entity Framework data model (edmx):

image

WCF RIA Services

With the entity model in place, use WCF RIA Services to generate the business classes and WCF communication code in your Silverlight project. You can then use the generated business classes in your Silverlight application for create, retrieve, update, delete (CRUD) operations.

1) Enable WCF RIA Services in your Silverlight application by setting the WCF RIA Services Link in the Silverlight project properties to reference the Silverlight Web project.

image

2) Build the solution.

NOTE: This is required or the Domain Service won’t know about your entity model and the following steps won’t work as expected.

3) In the Web project, build a Domain Service class for one of your entities.

image

4) Select the appropriate entities from the resulting dialog:

image

Since Step 3 identified a StudentService class, Step 4 selects the Student entity. If you want your Silverlight code to change the data, be sure to check "Enable editing". Leave it unchecked if you want read-only data.

When you click OK, Visual Studio generates the service code in VB.NET or C#.

5) Repeat steps 3 and 4 for each entity.

If you want to build along with this example, add a ScoreService  that references the Score entity and a ScoreTitleService that references the ScoreTitle entity. Be sure to check "Enable editing" for both of them.

Silverlight

Wow! Quite a bit of work. But we are finally ready to hook the data to the Silverlight user interface.

1) Add a page to your Silverlight project that will allow the user to review or edit student information.

If you are working through the set of blog posts, add a new Page called Students. (Be sure to add a link from the main page to this page using the technique from this prior post.)

2) When the Silverlight page is active in the designer, show the available Data Sources: Data | Show Data Sources.

There should be a data source for each domain service you added above.

image

3) Drag and drop the Student data source onto the page.

image

Silverlight generates the UI, including all of the required binding. By default, it adds controls for each field in the table in alphabetical order. You can delete, or re-arrange as desired.

NOTE: If you want to define the desired order of the columns BEFORE dragging and dropping the grid onto the form, you can edit the generated metadata file. In the Web project, locate the StudentService.metadata.cs or StudentService.metadata.vb file. If you don’t see the metadata files, recompile to generate them. Add attributes onto the properties as shown below and recompile.

In C#:

[Display(Order=3)]
public Nullable<int> Age { get; set; }

[Display(Order=2)]
public string Email { get; set; }

[Display(Order=0)]
public string FirstName { get; set; }

[Display(Order=1)]
public string LastName { get; set; }

In VB:

<Display(Order:=3)>
Public Property Age As Nullable(Of Integer)

<Display(Order:=2)>
Public Property Email As String

<Display(Order:=0)>
Public Property FirstName As String

<Display(Order:=1)>
Public Property LastName As String

4) Run the application.

image

Now the real question is … how the heck did that work?

The xaml that was generated in Step 3 above includes a DomainDataSource control:

<riaControls:DomainDataSource AutoLoad="True"
     d:DesignData="{d:DesignInstance my:Student, CreateList=true}"
     Height="0"
     LoadedData="studentDomainDataSource_LoadedData"
     Name="studentDomainDataSource"
    
QueryName="GetStudentsQuery"
     Width="0">
    <riaControls:DomainDataSource.DomainContext>
        <my:StudentContext />
    </riaControls:DomainDataSource.DomainContext>

The code items shown in bold are the most important. The QueryName property defines the query that is executed to obtain the data. The DomainContext property defines the name of the class containing that query method. But try to locate either of those in your code and you won’t find them.

Select the Silverlight project in Solution Explorer and click on the Show All Files button in the Solution Explorer toolbar.The Generated_Code folder then appears. In that folder is an InStepSM.SL.Web.g.cs or InStepSM.SL.Web.g.vb file. That file contains all of the code in the Silverlight project that was generated by Visual Studio from the information in the domain service classes. That code contains the StudentContext class which has the GetStudentsQuery method referenced by the DomainDataSource control.

The GetStudentsQuery method uses WCF to call the Web project’s StudentService which in turn uses EF to retrieve the data and return it to the Silverlight project. The binding in the xaml does the rest.

Use the steps above any time you want to use EF and WCF RIA Services to access data in your application.

Click here to download the associated source code.

Enjoy!

EDIT 2/5/2011: Added a few more columns to the Student table to make the later update features more interesting. Also added a note about editing the metadata.

EDIT 2/8/2011: Added the link to the source code.

3 Comments

  1.   Dhinesh Kumar — January 31, 2011 @ 3:19 am    Reply

    Hello Deborah

    Is it possible to share Instep project with us ?

    regards
    Dhinesh Kumar

  2.   DeborahK — January 31, 2011 @ 11:00 am    Reply

    Hi Dhinesh –
    Yes, I plan to provide the project source code. I have a few more posts, including one to show data updates. Then I will have a “complete” project that I will be posting.

  3.   Joe — February 24, 2011 @ 1:34 am    Reply

    Followed the steps, and everything looked just as in your examples.

    Up until the Data >> Show DataSources

    The DataSources pane is empty. And I cannot figure out how to get the Domain services to show.

    edit: decided to try one more thing. Saved the app, closed it, then closed VS. When I reopened the app, the Domain services were in the DataSources pane

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs