News


 PREREQUISITES DEVELOPPMENT TOOL 

In this tutorial, component that follow is required and need to be install: 

  • Visual Studio 2010 Express
  • ADO.NET Entity Framework 3.5/4.0
  • Microsoft Silverlight 4 Tools for visual Studio 2010 that include all components necessary for silverlight 4: Silverlight 4 developper runtime, silverlight 4 SDK, silverlight 4 tools for visual studion 2010. Please, to download it, please refer to this link.

 INTRODUCTION 

This topic explain in the simple way how to display data from two tables with relationship in application silverlight. I used ADO.NET Entity Framework to retrieve data and create the Silverlight DataGrid.

 GETTING START

Once all requires installers have been done, you started creating new project web application in which the control silverlight is hosted. You can find here the Sql Database called "Sale.mdf" used in this tuto . Please note that step to generate edmx model Entity Framework is not mentioned in this article. If you need more information how to perfom this step, please refer to this link

 CREATING HOSTED SILVERLIGHT APPLICATION

We will start creating new ASP.NET web application in Visual Studio 2010.

  • click "New project" in the Menu bar
  • Select "ASP.NET Web Application" and name the application as "SilverlightTuto".

 

  • Click "OK" button

 SET UP EDMX MODEL ENTITY FRAMEWORK

  • Fist, create new "Class Library" project name "DAL" layer. This is where your Entity Model(edmx) will be placed
  • Click "OK" button
  • Add new Item "ADO.NET Entity Data Model" to the "DAL" project. Follow this link for more information concering how to create edmx data model. 

I have created a simple database table with relationship to illustrate the process master/details when displaying on DataGrid Silverlight. Here is a view of what the table schema looks like in Sql Server:

 

After generating your entity model to your database and adding these tables to your edmx model, your model should look like this when you are done.

 

 

 That's all about creating edmx model Entity Framework in visualt studio 2010.

  SETTING REFERENCE

You cannot set direclty a reference from DAL to SilverlightTuto project for the simple reason that you are working on the client side at runtime. Moreover, non Silverlight assembly cannot be used to a Silverlight project because CLR for .NET application and Silverlight are different.

The solution is to use RIA Services. In this article we use WCF service technologie to consumme data from client-side.

 CREATING THE WCF SERVICE PROJECT

  • Add new project in the solution.
  • Select "WCF" project and name the application as "SilverlightTuto.WcfService"

  • Visual studio genere automatically for you two source files:
      • IService1.cs : it is an Interface between client side(silverlight) and server-side (DB)
      • Service1.svc.cs: implementation of the IService1 interface.
  • Add a reference from "SilverlightTuto.WcfServive to your Data Access Layer project. And also add a reference "System.Data.Entity" to the project.
  •  

     

  • Adding the following methods inside IService1.cs file: 

  •  The implementation of these contract will be defined inside the Service1.svc.cs file:
   1: public class Service1 : IService1
   2:     {
   3:         /// <summary>
   4:         /// A reference to the Data Access Layer project
   5:         /// </summary>
   6:         private SaleEntitiesContext cxt;
   7:  
   8:         /// <summary>
   9:         /// Initialize a new instance of <see cref="Service1"/> class.
  10:         /// </summary>
  11:         public Service1()
  12:         {
  13:             cxt = new SaleEntitiesContext("name=SaleEntities"); 
  14:            // SaleEntities is the name of your data model.
  15:         }
  16:  
  17:         /// <summary>
  18:         /// Get customers list in database
  19:         /// </summary>
  20:         /// <returns></returns>
  21:         public List<Customer> GetCustomers()
  22:         {
  23:             try
  24:             {
  25:                 var customers = (from cust in cxt.Customers
  26:                                  select cust);
  27:  
  28:                 return customers.ToList();
  29:             }
  30:             catch (DbException e)
  31:             {
  32:                 throw new FaultException(
  33:                 new FaultReason(e.Message),
  34:                 new FaultCode("Data Access Error"));
  35:             }
  36:         }
  37:          
  38:         /// <summary>
  39:         /// Get Product purchased by the Customer
  40:         /// </summary>
  41:         /// <param name="CustomerID"></param>
  42:         /// <returns></returns>
  43:         public List<Product> GetProduct(int CustomerID)
  44:         {
  45:             var product = (from p in cxt.Products
  46:                            where p.CustomerID == CustomerID
  47:                            select p).ToList();
  48:             return product;
  49:         }
  50:  
  51:  
  52:     }

We have created a WCF project and Silverlight application project. Now, let's see how to link these two project.

  • Compile the service before adding it to the Silverlight project.
  • Right click on the "SilverlightTuto" project and then choose "Add Service Reference"
  • A new Dialog box will appear. Click on button "Discover" to a add service in a solution 

 

The "SilverlightTuto" project after adding the service reference:

 

 BUILDING THE USER INTERFACE 

The first thing you need to do is get the DataGrid and ComboBox onto your Silverlight Control. DataGrid will display data from Product table. ComboxBox will be used to display customer list. For that add the following XAML code to the MainPage.xaml.

 

All right, now let's add the following code to the MainPage.xaml.cs:

 Note that, in silverlight, services should be called only using asynchronous. 

Here is the overall project structure:

 SCREEN OUTPUT 

Following comboBox value selected, the DataGrid display the products purchased by the customer.

 

 CONCLUSION

That's all about consuming the ADO.NET Entity Framework from Silverlight application using WCF service. Although i have not detailed a few steps necessary, for exemple how to generate the model edmx file entity framework, i hope you will get some understanding about how to bind, from tables relationship, Datagrid Silverlight using WCF that provide data to retrieve using Entity Framework. This is the purpose of writing this article.

 

 

 

 


Comments

Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Ted Borlongan on 8/26/2011 12:54 AM
Good. But I hope you have exposed the code for asynchronous execution the actual code that implements your service contract. Thanks.
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Berthin on 8/27/2011 1:37 AM
Hi, thanks for your comment. You're right,so i post below the service contract methods's implementation.
/// <summary>
/// Get customers list in database
/// </summary>
public List<Customer> GetCustomers()
{
var customers = (from cust in cxt.Customers
select cust);
return customers.ToList();
}

/// <summary>
/// Get Product purchased by the Customer
/// </summary>
/// <param name="CustomerID"></param>
public List<Product> GetProduct(int CustomerID)
{
var product = (from p in cxt.Products
where p.CustomerID == CustomerID
select p).ToList();
return product;
}
So if you have something not clear , please just drop a comment in the post , i will get back to you as soon as i can.
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Mayank on 9/8/2011 12:53 AM
Hi Berthin,

Wonderful post. Could you please post the code of the WCF service as well. I could see only Interface information of the service.

Also, what exactly is cxt in the above comment?

Thanks
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Berthin on 9/16/2011 11:41 PM
Hi Mayank,
In my above comment, you will find the code of the WCF service.

When generating entity data model from Entity Data Model Wizard provided by visual studio, a class (here 'cxt') will be auto-generated. This class inherits from ObjectContext class which contains an Entity Connection(to connect to the database), the model metadata and an ObjectStateManager for tracking chages to the objects(or Entities) during CREATE, DELETE, or UPDATE operations.
Within the 'cxt' class, you have all entities which represents all database objects.
For more details, please refer to http://thedatafarm.com/LearnEntityFramework/tutorials/creating-an-ado-net-entity-framework-entity-data-model

Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Emmanuel on 9/20/2011 6:37 AM
I have tried this example but it doesn't seem to execute the asynchronous call to the service, another possibility is that there is something wrong with the database server although I've tested the connection and it works fine (plus I created the entity model with no problem), point is, I'm not getting any data back. I'm using Sybase ASE 15.5 Cluster Edition
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by thomosbin on 9/20/2011 7:38 PM
This information is quite helpful for the students like us who are preparing for this exam.
I will surely try it and post my reviews very soon.
how do you get rid of skin
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Palitha Abeysinghe on 11/12/2011 6:53 AM
What is RIA Services and How can we use that beahlf of the WCF services
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Ramesh on 11/21/2011 10:29 PM
I did the same. But when i call the service methods in silverlight i m getting the following error
The remote server returned an error: NotFound.

i feel problem with when i call the method which return List<T>. If call a method which will return string is not giving the problem.

MY interface

[ServiceContract]

public interface IResumeService
{

[OperationContract]
string GetData(int value);


[OperationContract]
List<Resume> GetResume(string keyword, bool isfreetext);

// TODO: Add your service operations here
implementation

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ResumeService : IResumeService
{
Entities _objEntity;
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}


List<Resume> IResumeService.GetResume(string keyword, bool isfreetext)
{
_objEntity = new Entities();
return _objEntity.SearchForResume(keyword, isfreetext).ToList();
}
}

what is the problem ? can u pls let me know ?



Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Berthin on 11/22/2011 9:33 AM
Hi Ramesh,there are a few possibilities causing this. To start make sure that the following code does not throw an error: add try catch block:_objEntity.SearchForResume(keyword, isfreetext).ToList();
Please test and let me know.
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Ramesh on 11/22/2011 11:11 PM
i created new solution and tried the same then it is working. i need to check with old. Moreover i have single table with 10 to 15 records. when i m trying this for both autocomplete and gridview. it is taking almost 90 seconds to load the data. also for autocomplete, for each key press i need to wait for 90 secs. may silverlight like this way only or i m missing something?

Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Cleaners Clapham on 1/11/2012 10:35 PM
This is appears to be very useful for many students in computer science. Thank you for sharing

Regards,
cleaners Kensington.
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Cleaners Kensington on 1/26/2012 2:10 AM
Great post and great guide. That is what I need for my exam tomorrow :)

Regards,
cleaners Anerley
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Jignesh Sodvadiya on 4/7/2012 9:11 PM
Dear All,
I facing problem with WCF RIA service is that if WCF service return large amount of data like 10000 record then Remote server error give at Silverlight app.
Please give related solution.

Thanks.
Jignesh
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Rod on 11/7/2012 4:54 AM
Please, tell me how and where cxt variable is declare?
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Berthin on 11/7/2012 6:32 AM
Hi Rod, I updated the topic. I added a section that will answer your question. Thanks.
Gravatar # re: Consuming ADO.NET Entity Framework from Silverlight
Posted by Brut on 2/17/2013 10:22 PM
Your project seems to crash due clienaccesspolicy... you could add word or two of that to this otherwise excellent example.
Comments have been closed on this topic.