How to: Define a Service Operation (WCF Data Services)


WCF Data Services expose methods that are defined on the server as service operations. Service operations allow a data service to provide access through a URI to a method that is defined on the server. To define a service operation, apply the [WebGet] or [WebInvoke] attribute to the method. To support query operators, the service operation must return an IQueryable<T> instance. Service operations may access the underlying data source through the CurrentDataSource property on the DataService<T>. For more information, see Service Operations.

The example in this topic defines a service operation named GetOrdersByCity that returns a filtered IQueryable<T> instance of Orders and related Order_Details objects. The example accesses the ObjectContext instance that is the data source for the Northwind sample data service. This service is created when you complete the WCF Data Services quickstart.

To define a service operation in the Northwind data service

  1. In the Northwind data service project, open the Northwind.svc file.

  2. In the Northwind class, define a service operation method named GetOrdersByCity as follows:

    [!CODE [Astoria Northwind Service#ServiceOperationDef](../CodeSnippet/VS_Snippets_Misc/astoria northwind service#serviceoperationdef)]

  3. In the InitializeService method of the Northwind class, add the following code to enable access to the service operation:

    [!CODE [Astoria Northwind Service#ServiceOperationConfig](../CodeSnippet/VS_Snippets_Misc/astoria northwind service#serviceoperationconfig)]

To query the GetOrdersByCity service operation

  • In a Web browser, enter one of the following URIs to invoke the service operation that is defined in the following example:

    • http://localhost:12345/Northwind.svc/GetOrdersByCity?city='London'

    • http://localhost:12345/Northwind.svc/GetOrdersByCity?city='London'&$top=2

    • http://localhost:12345/Northwind.svc/GetOrdersByCity?city='London'&$expand=Order_Details&$orderby=RequiredDate desc

The following example implements a service operation named GetOrderByCity on the Northwind data service. This operation uses the ADO.NET Entity Framework to return a set of Orders and related Order_Details objects as an IQueryable<T> instance based on the provided city name.

System_CAPS_ICON_note.jpg Note

Query operators are supported on this service operation endpoint because the method returns an IQueryable<T> instance.

[!CODE [Astoria Northwind Service#ServiceOperation](../CodeSnippet/VS_Snippets_Misc/astoria northwind service#serviceoperation)]

Defining WCF Data Services