如何:定义服务操作(WCF 数据服务)
WCF 数据服务 公开在服务器上作为服务操作定义的方法。 服务操作允许数据服务通过 URI 提供对服务器上定义的方法的访问。 若要定义服务操作,请对方法应用 [WebGet] 或 [WebInvoke] 特性。 若要支持查询运算符,服务操作必须返回一个 IQueryable<T> 实例。 服务操作可以通过 DataService<T> 的 CurrentDataSource 属性访问基础数据源。有关详细信息,请参阅服务操作(WCF 数据服务)。
本主题中的示例定义一个名为 GetOrdersByCity 的服务操作,该操作返回 Orders 和相关 Order_Details 对象的经筛选后的 IQueryable<T> 实例。 该示例访问作为 Northwind 示例数据服务数据源的 ObjectContext 实例。 此服务是在完成 WCF 数据服务快速入门时创建的。
在 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 实体框架返回一组 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));
}
}