Jun 24

Written by: Michael Washington
6/24/2011 6:08 AM  RssIcon

image

Also see: WCF RIA Service: Combining Two Tables (an example of connecting to the LightSwitch database)

WCF RIA Services are the “fix any data issue” solution. If the problem is getting data to your LightSwitch application, and the normal create or add table will not work, the answer is to use a WCF RIA Service.

See: Creating A WCF RIA Service Using Entity Framework for an example of using a WCF RIA Service with Entity Framework (EF).

In this Blog post, we will create a simple WCF RIA Service that is not hooked up to a database. We will use POCO (Plain Old CLR Objects). We will do this to demonstrate just the WCF RIA Service interaction with LightSwitch.

image

First, we create a new LightSwitch project.

image

We add a New Project.

image

We add a Class Library.

image

Delete the Class1 file that is created.

image

Add a New Item to the project.

image

Add a Domain Service Class.

image

When the Add New Domain Service Class box comes up, uncheck Enable client access. Click OK.

image

The code window will show.

Add the following code:

 

image

 

    public class CustomerRecord
    {
        [Key]
        public int CustomerID { get; set; }
        public string CustomerName { get; set; }
        public string CustomerEmail { get; set; }
        public string CustomerNotes { get; set; }
        public DateTime CustomerLastContact { get; set; }
    }
 

Notice the CustomerID is decorated with the [Key] attribute. You must have a field marked as a Key to be used as a LightSwitch data source.

 

Next, Add the following code to the class to create sample data:

 

image

 

        private readonly List<CustomerRecord> _sampleCustomerRecordList;
        public CustomerDomainService()
        {
            _sampleCustomerRecordList = new List<CustomerRecord>();
            for (int i = 0; i < 100; i++)
            {
                CustomerRecord CR = new CustomerRecord();
                CR.CustomerID = i;
                CR.CustomerName = string.Format("FirstName{0} LastName{1}", i.ToString(), i.ToString());
                CR.CustomerEmail = string.Format("Email{0}@{1}.com", i.ToString(), i.ToString());
                CR.CustomerNotes = string.Format("Notes {0}. Notes {1}", i.ToString(), i.ToString());
                CR.CustomerLastContact = DateTime.Now.AddDays(-10000).AddHours(i);
                _sampleCustomerRecordList.Add(CR);
            }
        }

 

Next Add the following method to allow LightSwitch to read the data:

 

        [Query(IsDefault = true)]
        public IQueryable<CustomerRecord> GetSampleCustomerData()
        {
            return _sampleCustomerRecordList.AsQueryable();
        }

 

Notice this is marked with the [Query(IsDefault = true)] attribute, One method must not require a parameter, and be marked with this attribute, to be used with LightSwitch.

Now we add Update and Delete methods:

 

        public void UpdateCustomerData(CustomerRecord objCustomerRecord)
        {
            var objResult = (from Customer in _sampleCustomerRecordList
                             where Customer.CustomerID == objCustomerRecord.CustomerID
                             select Customer).FirstOrDefault();
            if (objResult != null)
            {
                objResult = objCustomerRecord;
            }
        }
        public void DeleteCustomerData(CustomerRecord objCustomerRecord)
        {
            var objResult = (from Customer in _sampleCustomerRecordList
                             where Customer.CustomerID == objCustomerRecord.CustomerID
                             select Customer).FirstOrDefault();
            if (objResult != null)
            {
                _sampleCustomerRecordList.Remove(objResult);
            }
        }

 

LightSwitch will know that these are Update and Delete methods, because they accept a customer object, return void, and have the words Update and Delete in the respective method names.

 

image

In the Solution Explorer, right-click on the Data Sources folder and select Add Data Source.

image

Select WCF RIA Service.

 

image

Click Add Reference.

 

image

Select the RIA Service project.

 

image

You have to wait for the service to show up in the selection box. Select it and click Next.

 

image

Check the boxes next to the Class, and click Finish.

 

image

The Entity will show up.

 

image

Add a Screen.

 

image

Add an Editable Grid Screen, and select the Entity for the Screen Data.

 

image

The Screen Designer will show.

 

image

When we hit the F5 key to run the application, we can update and delete records.

However, when we press Refresh, the records return to normal because in this example the update and delete do not actually change the sample data.

Also see: WCF RIA Service: Combining Two Tables (an example of connecting to the LightSwitch database)

Download

The LightSwitch project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

39 comment(s) so far...


Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Could this be used with the POCO's generated from [b]ADO.NET C# POCO Entity Generator[/b](http://visualstudiogallery.msdn.microsoft.com/23df0450-5677-4926-96cc-173d02752313)?

By Refracted Paladin on   6/28/2011 7:16 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@Refracted Paladin - I don't know. However, it should work.

By Michael Washington on   6/28/2011 7:25 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Thanks for all of your work. You make it look easy!

By fishy on   6/28/2011 7:29 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@fishy - It is! Haha

By Michael Washington on   6/28/2011 7:30 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Can you combine WCF RIA services with database entities in the datasource designer?

thanks

By fishy on   6/28/2011 9:32 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@fishy - No

By Michael Washington on   6/28/2011 9:39 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

I stumbled across this article that looks like you can have both:
http://powerbala.com/2011/04/10/many-to-many-control-for-microsoft-lightswitch/

By fishy on   6/28/2011 11:57 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@fishy - I am sorry I should have been clear, you cannot have them in the same datasource. LightSwitch puts them in seperate datasources. However, yes you can have multiple datasources on the same screen.

By Michael Washington on   6/28/2011 12:06 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

I'am looking for lighswitch applicaiton using external web services RIA Services - the one I found on powerbala.com using the ZIPcode webservices is not working - I would appreicate if you can send me url of
External web services used in Lightswitch.

By Ramesh on   8/15/2011 7:01 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@Ramesh - You can try: http://blogs.msdn.com/b/lightswitch/archive/2010/10/22/how-to-create-a-ria-service-wrapper-for-odata-source.aspx

By Michael Washington on   8/15/2011 7:29 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Thanks for url. What I was looking for is on the lines of
http://powerbala.com/2011/04/16/calling-a-3rd-web-service-from-lightswitch/
I see that in that blog you have added comments - If you have got it working I would appreciate if you can send me the zip file (ria class) to my email ( r_vodela@yahoo.com)

By Ramesh on   8/16/2011 9:55 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Why can't I print your blog pages with Firefox? The pages are all empty.

Peter

By Peter on   8/21/2011 4:15 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Thanks for this tutorial. I'm a little stump at the beginning with a 'simple' problem. I do not see the option to add a "Domain Service Class" when adding an item to the RIA service. What can I do in that instance?

By CT on   8/29/2011 7:49 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@CT - You must have Visual Studio Pro (or higher). If you do then download the code from the download page on this site and try it with that project.

By Michael Washington on   8/29/2011 7:51 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

I have problems with paging with POCOs in my project so I've tried your example to see the difference, but with your sample it's exactly the same problem. I just see the first page and the pager says 1 of 1 although there are more pages. I think I've overlooked something obvious. May be you can give me a hint.

By Uwe Helmut on   9/7/2011 11:43 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@Uwe Helmut - see the "protected override int Count(IQueryable query)" method at:
http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/47/WCF-RIA-Service-Combining-Two-Tables.aspx

By Michael Washington on   9/7/2011 11:59 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Thanks a lot. I've missed that one.

By Uwe Helmut on   9/7/2011 12:49 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Hi,

Is there a possibility of having other query methods which takes say string or int parameters and executes something on a DB - Called from the front-end and executed in the Service. I believe it should be, however I have encountered this odd situation where method like such that I have created are visible from the lightswitch app, but whenever I try to use it i get "object reference not sent to an instance of the object" on the Method.

Sample:

In DomainService

[Query]
public IEnumerable GetReport(DateTime? date)
{
return new List();
}

In Report Screen

ReportData rd = new ReportData();
rd.GetReport(DateTime.Now); // <---- Error Here

The error is on the GetReport.

Any help?


By spidergeuse on   9/29/2011 4:02 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@spidergeuse - You can't just return "new List();". You have to declare a concrete class and return that.

By Michael Washington on   9/29/2011 4:05 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Hello,

actually I'm returning a concrete object, called Report.

I believe this is not what i posted. The brower must have processed my tags.

Well so that the > and GetReport(DateTime? date)
{
   return new List ();
}

In Report Screen

ReportData rd = new ReportData();
rd.GetReport(DateTime.Now); // <---- Error Here

The error is on the GetReport.




Thanks very much for your help

By @spidergeuse on   9/29/2011 3:27 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@spidergeuse - The only thing I can think of is that there may be no need for "ReportData rd = new ReportData();" Just place the collection on the Screen and then call it. If that is not it, you may need to Google the setting in LightSwitch that allows saving to multiple data sources. Again I am just not sure.

By Michael Washington on   9/29/2011 3:30 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Hey,
I want to ask if I can call a nonquery stored procedure from LS. I mean i will create a button, a method and with Ria Services, I will call an SP. Is it possible and how and if there is a resource can you please direct me .
Cheers

By Cüneyt Gargın on   10/4/2011 12:21 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@Cüneyt Gargın - Yes, but I have no code examples.

By Michael Washington on   10/4/2011 12:22 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Michael,

Thanks for putting this together. I am finding the site as a whole to be very helpful. This one post helped me get my brain wrapped around what is required to get a WCF RIA service exposed to LightSwitch. I will be reading some of the other posts to get a handle on Silverlight controls as well.

But thanks again for the example. Straight to the point with no clutter. Very good.

Kevin

By Kevin B. on   10/13/2011 7:29 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@Kevin B. - Thank you for the feedback and kind words.

By Michael Washington on   10/13/2011 7:29 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

How exactly does LightSwitch know that the CustomerRecord class is a DomainService entity? Is it purely the [Key] attribute?

By James on   11/9/2011 8:24 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@James - The IQueryable method signature return type is what lets "LightSwitch know that the CustomerRecord class is a DomainService entity".

By Michael Washington on   11/9/2011 8:28 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Hello Crew,

I wonder if you can make a video's collections , about first how to make Wfc Ria Services , in both language C and Vb
second how to make a report in Lightswitch word or pdf, third how to make secreen template , i mean videos and not a topics.

I know its perhaps difficult or , you ask your self why i will do such videos , but believe me there a lot of people or student waiting for such video's.

Please think about it , thrie thing Ria Services, screen template , and lightswitch word, i know that you coverd all this here in this website , but for the beginners is quit difficult to follow the topics.


Best Regardes

Nasser

By Nasser Wahby on   5/13/2012 2:05 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@Nasser Wahby - The problem is that I hate videos :) Most of these tutorials I do for myself because I need to write down the information for future use :)

By Michael Washington on   5/13/2012 2:07 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

I definitely work better from photos. I followed through the example and succeeded quite easily. Then I got emboldened and created a RIA service to get data from a non-DB data source. I learned how easy it was to convert the data to a dictionary and create a queryable object using the Dictionary.AsQueryable() method to satisfy the public IQueryable method of the service. Setting a unique index wasn't all that hard. This is pretty exciting stuff!

By Harold on   5/15/2012 1:43 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@Harold - Glad it helped. I also work better from photos :)

By Michael Washington on   5/15/2012 1:43 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

What if I wanted to add a record? And if a record is added how does the WCF RIA return an auto generated ID back to lightswitch so it knows to update the added record with the new ID?

By Kyle on   8/23/2012 3:21 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@Kyle - See the other WCF RIA Services articles for an example of adding new records.

By Michael Washington on   8/23/2012 3:21 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

I am using code-first. I got as far as the Available service classes showing the correct data context but when I click the next button I get the following error:

The type WeiseData.DomainService1 could not be loaded. The assembly containing the class may be missing or may have additional references which are missing.

Now, I can't seem to even see the context pop up any more. I have been waiting a couple mins already.

By jaime weise on   10/25/2012 5:02 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)


I tried this using VS 2012, but when it gets to adding data source and selecting the project reference nothing is shown in the available WCF Ria Service classes. Installed Lighswitch 2011 and used VS 2010 and it works as it should do. However, installing the Lightswitch 2011 has broken the 2012 completely as I cannot create a new Lightswitch project in VS 2012. Seems to be a compatibility issue with the two side by side, any ideas?

By Rob on   11/13/2012 9:20 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

@Rob - Sorry no ideas :( It works for me everyday.

By Michael Washington on   11/13/2012 9:20 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

I have 4 tables budgetYear,Country,Crop ,CropCountryMapping

BudgetYear has BudgetYearId,Year
Country has CountryID ,CountryName
Crop has CropID,CropName
CropCountryMapping has ID,CropID,CountryID BudgetYearId


In one Screen I havev 3 DropDowns
1st is BudgetYear
and 2nd is Country dropdown

on Select of above two Dropdowns i want to fill the 3rd dropdown with crops table Data Using CropCountryMapping table by passing BudgetYearId,CountryID

How can i achieve this Scenario in lightswitch

If we need to Use RIA service to fill the crops dropdown baseed on year and country

Can i use ligthswitch2011 to create a RIA service

How can i bind dropdown using RIA service

can i use dropdown selected value in the save to save in the Another table (Not RIA service)

Please answer ASAP as struck in the middle of task.

By sreeman on   11/21/2012 5:17 AM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Thank you.

By George on   4/10/2013 1:32 PM
Gravatar

Re: Creating a Simple LightSwitch RIA Service (using POCO)

Great article Michael. Thank you for presenting an introduction to WCF RIA Services with such clarity.
I would like to point out that in case that someone uses VS 2012 in order the RIAService.CustomerDomainService class to be presented as Available WCF RIA Service class, you must first select properties of RIAService project and then select Target framework => .NET Framework 4.
In case RIAService targets .NET Framework 4.5 you cannot add the data source (It is mentioned as a Warning that the referenced project 'RIAService is targeting a higher framework version (4.5) than this project's current target framework version (4.0)).

By Vassilis Tsolekas on   6/17/2014 12:52 AM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 
Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation