HOW TO:定義服務作業 (WCF Data Services)
WCF Data Services 會將伺服器上定義的方法公開為服務作業。 服務作業可讓資料服務透過 URI 存取在伺服器上定義的方法。 若要定義服務作業,請將 [WebGet] 或 [WebInvoke] 屬性套用至方法。 若要支援查詢運算子,服務作業必須傳回 IQueryable<T> 執行個體。 服務作業可以透過 DataService<T> 上的 CurrentDataSource 屬性存取基礎資料來源。如需詳細資訊,請參閱服務作業 (WCF Data Services)。
本主題的範例定義名為 GetOrdersByCity 的服務作業,此服務作業會針對 Orders 執行個體傳回篩選過的 IQueryable<T>,以及相關的 Order_Details 物件。 此範例存取的 ObjectContext 執行個體為 Northwind 範例資料服務的資料來源。 此服務會在您完成 WCF Data Services 快速入門時建立。
在 Northwind 資料服務中定義服務作業
在 Northwind 資料服務專案中,開啟 Northwind.svc 檔案。
在 Northwind 類別中,定義名為 GetOrdersByCity 的服務作業方法,如下所示:
<WebGet()> _ Public Function GetOrdersByCity(ByVal city As String) As IQueryable(Of Order)
[WebGet] public IQueryable<Order> GetOrdersByCity(string city)
在 Northwind 類別的InitializeService 方法中加入下列程式碼,以存取服務作業:
config.SetServiceOperationAccessRule( _ "GetOrdersByCity", ServiceOperationRights.AllRead)
config.SetServiceOperationAccessRule( "GetOrdersByCity", ServiceOperationRights.AllRead);
查詢 GetOrdersByCity 服務作業
在 Web 瀏覽器中輸入下列其中一個 URI,叫用在下列範例中定義的服務作業:
https://localhost:12345/Northwind.svc/GetOrdersByCity?city='London'
https://localhost:12345/Northwind.svc/GetOrdersByCity?city='London'&$top=2
https://localhost:12345/Northwind.svc/GetOrdersByCity?city='London'&$expand=Order_Details&$orderby=RequiredDate desc
範例
下列範例會在 Northwind 資料服務實作名為 GetOrderByCity 的服務作業。 此作業使用 ADO.NET Entity Framework,根據所提供的城市名稱傳回一組 Orders 和相關的 Order_Details 物件,做為 IQueryable<T> 執行個體。
注意
此服務作業端點支援查詢運算子,因為方法會傳回 IQueryable<T> 執行個體。
<WebGet()> _
Public Function GetOrdersByCity(ByVal city As String) As IQueryable(Of Order)
If String.IsNullOrEmpty(city) Then
Throw New ArgumentNullException("city", _
"You must provide a value for the parameter'city'.")
End If
' Get the ObjectContext that is the data source for the service.
Dim context As NorthwindEntities = Me.CurrentDataSource
Try
Dim selectedOrders = From order In context.Orders.Include("Order_Details") _
Where order.Customer.City = city _
Select order
Return selectedOrders
Catch ex As Exception
Throw New ApplicationException("An error occurred: {0}", ex)
End Try
End Function
[WebGet]
public IQueryable<Order> GetOrdersByCity(string city)
{
if (string.IsNullOrEmpty(city))
{
throw new ArgumentNullException("city",
"You must provide a value for the parameter'city'.");
}
// Get the ObjectContext that is the data source for the service.
NorthwindEntities context = this.CurrentDataSource;
try
{
var selectedOrders = from order in context.Orders.Include("Order_Details")
where order.Customer.City == city
select order;
return selectedOrders;
}
catch (Exception ex)
{
throw new ApplicationException(string.Format(
"An error occurred: {0}", ex.Message));
}
}