DataServiceQuery<TElement>.AddQueryOption(String, Object) Метод

Определение

Создает новый запрос DataServiceQuery<TElement> с параметром запроса, заданным в URI, который был сформирован возвращенным запросом.

public:
 System::Data::Services::Client::DataServiceQuery<TElement> ^ AddQueryOption(System::String ^ name, System::Object ^ value);
public System.Data.Services.Client.DataServiceQuery<TElement> AddQueryOption (string name, object value);
member this.AddQueryOption : string * obj -> System.Data.Services.Client.DataServiceQuery<'Element>
Public Function AddQueryOption (name As String, value As Object) As DataServiceQuery(Of TElement)

Параметры

name
String

Строковое значение, содержащее имя добавляемого параметра строки запроса.

value
Object

Объект, содержащий значение параметра строки запроса.

Возвращаемое значение

Новый запрос, включающий запрошенный параметр запроса, добавленный к универсальному коду ресурса (URI) предоставленного запроса.

Примеры

Следующий пример иллюстрирует запрос DataServiceQuery<TElement> с последующими вызовами метода AddQueryOption, приводящими к возврату только заказов с ценой доставки, превышающей 30 долларов, упорядоченных по дате поставки в убывающем порядке.

// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Define a query for orders with a Freight value greater than 30
// and that is ordered by the ship date, descending.
DataServiceQuery<Order> selectedOrders = context.Orders
    .AddQueryOption("$filter", "Freight gt 30")
    .AddQueryOption("$orderby", "OrderID desc");

try
{
    // Enumerate over the results of the query.
    foreach (Order order in selectedOrders)
    {
        Console.WriteLine("Order ID: {0} - Ship Date: {1} - Freight: {2}",
            order.OrderID, order.ShippedDate, order.Freight);
    }
}
catch (DataServiceQueryException ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}
' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)

' Define a query for orders with a Freight value greater than 30
' and that is ordered by the ship date, descending.
Dim selectedOrders As DataServiceQuery(Of Order) = context.Orders _
.AddQueryOption("$filter", "Freight gt 30") _
.AddQueryOption("$orderby", "OrderID desc")

Try
    ' Enumerate over the results of the query.
    For Each order As Order In selectedOrders
        Console.WriteLine("Order ID: {0} - Ship Date: {1} - Freight: {2}", _
                order.OrderID, order.ShippedDate, order.Freight)
    Next
Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
            "An error occurred during query execution.", ex)
End Try

Следующий пример показывает, как создать запрос LINQ, эквивалентный предыдущему запросу с использованием метода AddQueryOption.

// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Define a query for orders with a Freight value greater than 30
// and that is ordered by the ship date, descending.
var selectedOrders = from o in context.Orders
                     where o.Freight > 30
                     orderby o.ShippedDate descending
                     select o;

try
{
    // Enumerate over the results of the query.
    foreach (Order order in selectedOrders)
    {
        Console.WriteLine("Order ID: {0} - Ship Date: {1} - Freight: {2}",
            order.OrderID, order.ShippedDate, order.Freight);
    }
}
catch (DataServiceQueryException ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}
' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)

' Define a query for orders with a Freight value greater than 30
' and that is ordered by the ship date, descending.
Dim selectedOrders = From o In context.Orders _
        Where (o.Freight > 30) _
        Order By o.ShippedDate Descending _
        Select o

Try
    ' Enumerate over the results of the query.
    For Each order As Order In selectedOrders
        Console.WriteLine("Order ID: {0} - Ship Date: {1} - Freight: {2}", _
                order.OrderID, order.ShippedDate, order.Freight)
    Next
Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
            "An error occurred during query execution.", ex)
End Try

Комментарии

Параметры запроса добавляются в результирующий URI с помощью ?name=value&name2=value2... синтаксис, в котором имя сопоставляется непосредственно с параметром namevalue , а получается путем вызова ToString для value параметра . Имя name начинается с $.

Синтаксис, отличный от WCF Data Services, не начинается с $. С помощью этого метода можно добавить параметры запроса, отличные от WCF Data Services. Если параметр не является WCF Data Services параметром запроса, то можно добавить один и тот же параметр запроса дважды. Если добавляется параметр запроса, который уже имеется в базовом URI, вызывается исключение.

Применяется к