Although in many cases you will want to work with the raw XML or JSON returned from a WDS service, it is easier to work with generated proxy classes. The generated proxy classes make it very easy to perform simple CRUD and query operations. Of course, behind the scenes they use HTTP.
Follow these steps to create an application to iterate through the Order objects using LINQ and the DataServiceContext class:
Add a new console application to the solution called Chapter9.ADOProxy.
Right-click the References folder.
Select Add Service Reference to add the URL your WDS is set up at (for example, http://localhost/Chapter9/MovieService.svc).
Enter the namespace MovieService, as shown in Figure 9-9.
Enter the following code to iterate through a list of Orders, printing the first name to the output window:
static void Main(string[] args) { DataServiceContext ctx = new DataServiceContext( new Uri("http://localhost/Chapter9/MovieService.svc") ); var Orders = ctx.Execute<MovieService.Models.Order>(new Uri("Orders", UriKind.Relative)); foreach (MovieService.Models.Order Order in Orders) { Console.WriteLine(Order.Firstname); } Console.ReadKey(); }
Press F5 to run the application; you should see a list of first names from the Orders table printed out.
Creating a new item using WCF Data Services is easy and just requires using the DataServiceContext's AddObject() and SaveChanges()methods:
static void Main(string[] args) { DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost/Chapter9/MovieService.svc")); MovieService.Models.Film NewFilm = new MovieService.Models.Film(); NewFilm.Title = "Pulp Fiction"; NewFilm.Length = 124; NewFilm.Description = "Quentin's classic movie"; ctx.AddObject("Films", NewFilm); ctx.SaveChanges(); }
To update an existing item, load an object, and then use the DataServiceContext's UpdateObject() and SaveChanges() methods:
static void Main(string[] args) { DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost/Chapter9/MovieService.svc")); MovieService.Models.Film FilmToUpdate = ctx.Execute<MovieService.Models.Film>(new Uri("Films(1)", UriKind.Relative)).First(); FilmToUpdate.Title = "Updated title"; ctx.UpdateObject(FilmToUpdate); ctx.SaveChanges(); }
To delete an item, use the DataServiceContext's DeleteObject() method with the SaveChanges() method (if you have defined any table constraints or rules, you will need to ensure you fulfill them; otherwise, this call will fail):
static void Main(string[] args) { DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost/Chapter9/MovieService.svc")); MovieService.Models.Film FilmToDelete = ctx.Execute<MovieService.Models.Film>(new Uri("Films(1)", UriKind.Relative)).First(); ctx.DeleteObject(FilmToDelete); ctx.SaveChanges(); }
18.219.123.84