Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

Silverlight Application with MVVM WCF and EF

Rate me:
Please Sign up or sign in to vote.
3.82/5 (16 votes)
17 Jun 2012CPOL4 min read 77.5K   3.6K   21   31
How to create a simple Silverlight application using the MVVM pattern with WCF and Entity Framework.

Introduction

In this article, we will see how to develop a simple Silverlight application with MVVM, WCF services, and Entity framework. In my earlier article, I described how to develop a simple Silverlight application in MVVM pattern (link to article). In this article, we will learn how to create a Silverlight application with WCF services also.

Steps

  1. Add a new Silverlight project.
  2. Create a project for Model as type Class Library.
  3. Add a WCF service project.
  4. Configure service.
  5. Add service reference to Silverlight project.
  6. Add cross domain policy.
  7. Run and debug the application.

Add a new  Silverlight project

  1. Create a new Silverlight project as below:
  2. Image 1

  3. Select Host application with website. This will include an ASPX project which we can use to host the Silverlight object.
  4. Image 2

  5. Now two projects would be created in the solution: Silverlight and web project.
  6. Image 3

Creating the Model Project

  1. Add a Class Library project to the solution.
  2. Image 4

  3. Add a .edmx file to the project.
  4. Image 5

  5. Now select the data source and tables to import.
  6. Image 6

    Image 7

  7. I am adding a schoolclass table to my entity model.
  8. Image 8

  9. Now you can see the Model1.edmx in the solution under the Model project and schoolclass entity in Model1.edmx.
  10. Image 9

Add the WCF service project

  1. Now add a WCF project to our solution.
  2. Image 10

  3. Now the service is added. You can see Iservice1, Service.svc, and service.svc.cs.
  4. Image 11

  5. Now I am going to write two methods in service. One is to get the class names and the other to get the school class details.
  6. C#
    [OperationContract]
    List<string> GetClasses();
  7. Now implement this methods in service1.svc.cs.
  8. C#
    public List<string> GetClasses()
    {
        SanthoshEntities entity = new SanthoshEntities();
        List<SchoolClass> list = entity.SchoolClasses.ToList();
        return list.Select(m => m.Name).ToList();
     }
    
    public List<SchoolClass> GetSchoolClasses()
    {
        SanthoshEntities entity = new SanthoshEntities();
        return entity.SchoolClasses.ToList();
    }
  9. Now you can see that we are getting errors, this is because we forgot to add a reference of the Model project here. So add a reference to the model and include in the .cs files.
  10. Image 12

    Image 13

Configure the service

  1. Configuring the service correctly is the critical thing. If we don’t configure properly, we will end up with different errors and it is very difficult to identify the issue.
  2. The first item we have to configure is the connection string. Copy the connection string created with edmx in the model project. Here you can configure different databases and servers. The server and database details don’t need to be the same in edmx config and service config.
  3. Image 14

    Image 15

  4. We need to configure the service. Add the below service details inside the system.servicemodel tag. Here the contract name should be the interface of the service with namespace.
  5. XML
    <services>
      <service name="WcfService.Service1">
        <endpoint address="" binding="basicHttpBinding" contract="WcfService.IService1" >
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
     </service>
    </services>
  6. So we are done with adding the model and service. Next we have to add this service as a reference to the Silverlight project. We have to build the project before adding this service as reference.
  7. So when I build the service, I get the below error. This is because we forgot to add System.Data.Entity as reference.
  8. Image 16

    Image 17

Add Service reference to Silverlight

  1. This is the easiest thing to do. Go to the Silverlight project, right click on Reference, and click on Add service reference.
  2. Image 18

  3. Here our service is in the same project so instead of typing the service address, I can click on Discover, so that Visual Studio will find the services in the same solution.
  4. Image 19

  5. Now update the namespace filed with the name you wanted and click on OK.
  6. Image 20

  7. Now you can see our service reference is added and the client.config file is also added. This will be the client side configuration of the service reference.
  8. Image 21

Setting up the Silverlight project

View and ViewModel

I created the View with a ListBox and GridView. The ListBox is to display class names and the school class is to display all the details about the school class. We have already seen about views and viewmodels in this article. Here we mainly discuss about using a service reference in the viewmodel.

In the constructor of the viewmodel, add a service client for the service reference. And since we want to load the ListBox and the GridView in page load itself, we can call the service reference methods also. In the callback event, assign the properties to the method Result.

C#
public MainViewModel()
{
    MyServiceReference.Service1Client client = new MyServiceReference.Service1Client();

    client.GetClassesCompleted += 
      new EventHandler<MyServiceReference.GetClassesCompletedEventArgs>(client_GetClassesCompleted);
    client.GetClassesAsync();
    client.GetSchoolClassesCompleted += 
      new EventHandler<GetSchoolClassesCompletedEventArgs>(client_GetSchoolClassesCompleted);
    client.GetSchoolClassesAsync();
}

void client_GetSchoolClassesCompleted(object sender, GetSchoolClassesCompletedEventArgs e)
{
    SchoolClasses = e.Result;
}

void client_GetClassesCompleted(object sender, MyServiceReference.GetClassesCompletedEventArgs e)
{
    Classes = e.Result;
}

For the complete view and viewmodel code, refer to the attached solution.

Now debug the application. It will give us the CommunicationException error. This is because of cross domain violation. When the service is located in some other project, we have to add the clientaccesspolicy.xml file. To know more about cross domain boundaries, refer to this Microsoft link:

Image 22

Add a new XML file and add the below code. Now run the application.

XML
<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Image 23

Image 24

Conclusion

In this article, we have seen how to create a simple Silverlight application using the MVVM pattern with WCF and Entity Framework. For the complete set of source code, please find the attached file.

Please give your valuable comments to improve the article and don’t forget to rate the article if you find it useful.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead EF (Education First)
India India
I graduated as Production Engineer and started my career as Software Developer then worked as tester for a while before moving into Windows application development using Microsoft Technologies. But for the last few years i am working on javascript, React, Node, AWS, Azure Chatbots

Comments and Discussions

 
GeneralMy vote of 2 Pin
Member 1313462117-Apr-17 20:34
Member 1313462117-Apr-17 20:34 
Questionby this way how saves change to database? Pin
Marziye vosooghian30-Oct-13 10:12
Marziye vosooghian30-Oct-13 10:12 
GeneralMy vote of 5 Pin
leojim198823-May-13 22:49
leojim198823-May-13 22:49 
QuestionHow to do it much more easy Pin
Mark Shneider17-May-13 12:34
Mark Shneider17-May-13 12:34 
GeneralMy vote of 2 Pin
ali_bahal21-Apr-13 4:06
ali_bahal21-Apr-13 4:06 
AnswerRe: My vote of 2 Pin
Santhosh Kumar Jayaraman21-Apr-13 21:24
Santhosh Kumar Jayaraman21-Apr-13 21:24 
QuestionImages Pin
MitchConner3-Dec-12 8:01
MitchConner3-Dec-12 8:01 
AnswerRe: Images Pin
Santhosh Kumar Jayaraman18-Dec-12 17:42
Santhosh Kumar Jayaraman18-Dec-12 17:42 
GeneralMy vote of 1 Pin
Ehsan yazdani rad3-Dec-12 2:01
Ehsan yazdani rad3-Dec-12 2:01 
GeneralRe: My vote of 1 Pin
Santhosh Kumar Jayaraman3-Dec-12 2:26
Santhosh Kumar Jayaraman3-Dec-12 2:26 
Questionwhat about validation using this approach ?? Pin
ganesh mahajan12-Nov-12 19:42
ganesh mahajan12-Nov-12 19:42 
Questionplease provide more about silverlight 5 Pin
giri444430-Oct-12 19:44
giri444430-Oct-12 19:44 
AnswerRe: please provide more about silverlight 5 Pin
Santhosh Kumar Jayaraman18-Dec-12 17:41
Santhosh Kumar Jayaraman18-Dec-12 17:41 
QuestionError Message Pin
osamaworx9-Oct-12 5:34
osamaworx9-Oct-12 5:34 
AnswerRe: Error Message Pin
Santhosh Kumar Jayaraman9-Oct-12 5:41
Santhosh Kumar Jayaraman9-Oct-12 5:41 
GeneralRe: Error Message Pin
osamaworx9-Oct-12 11:24
osamaworx9-Oct-12 11:24 
In fact I did not follow typical steps as you said but this article was very helpful for me
specially in configuration step .
My case was different
I need to build two separated projects that will host on two different machines
First machine: Is server will host database and WCF
Second machine is another server that will host the Silverlight Client [Silverlight Application without ASP website]
Normal PC’s will access Silverlight app from browsers
Silverlight App fore Shure must reach to WCF that stored in first server with right configurations
And this is exactly my problem
What I really need is a small Example that has two separated projects
First is WCF project
Second is Silverlight project not hosted on ASP website
I do small Example for test.
Using .Net Framework 4 ,VS 2012 , Silverlight 5 .
That example is:
----------------------------------------------------------------------------------------------
Database table [user]: ID ,Name ,Password
WCF that have function bool Login(username,password) :
[return true if username and password exist in table ,false otherwise]
Silverlight Application : username textbox ,password textbox ,result textbox ,button
Scenario
button will take
[usernametextbox.text , passwordtextbox.text , pass this strings to WCF and return true or false in resulttextbox]
----------------------------------------------------------------------------------------------
After building this sample I use the your article configuration’s then I got that ugly error
This Link have my sample project. Can you help me please?
http://www.mediafire.com/file/telcq7zul7tadrt/Login.rar
and what is InnerException ?

modified 9-Oct-12 17:48pm.

GeneralRe: Error Message Pin
osamaworx9-Oct-12 11:25
osamaworx9-Oct-12 11:25 
GeneralInner Exception Pin
osamaworx11-Oct-12 0:36
osamaworx11-Oct-12 0:36 
AnswerRe: Inner Exception Pin
Santhosh Kumar Jayaraman11-Oct-12 0:47
Santhosh Kumar Jayaraman11-Oct-12 0:47 
GeneralRe: Inner Exception Pin
osamaworx11-Oct-12 4:38
osamaworx11-Oct-12 4:38 
QuestionProblem Adding Service Reference Pin
Tom Bean2-Oct-12 5:54
Tom Bean2-Oct-12 5:54 
AnswerRe: Problem Adding Service Reference Pin
Santhosh Kumar Jayaraman2-Oct-12 22:49
Santhosh Kumar Jayaraman2-Oct-12 22:49 
GeneralNice article Pin
vijayasaladi from hyderabad25-Sep-12 2:00
vijayasaladi from hyderabad25-Sep-12 2:00 
GeneralRe: Nice article Pin
Santhosh Kumar Jayaraman25-Sep-12 2:05
Santhosh Kumar Jayaraman25-Sep-12 2:05 
GeneralMy vote of 1 Pin
Ahmad Habash17-Sep-12 8:39
Ahmad Habash17-Sep-12 8:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.