Как выполнять запросы к службе данных (службы WCF Data Services)

Службы Службы WCF Data Services позволяют выполнять запросы к службе данных из клиентского приложения на основе .NET Framework с использованием сформированных клиентских классов службы данных. Выполнять запросы можно одним из следующих способов.

  • Выполнение запроса LINQ к именованному объекту DataServiceQuery, который получен из контекста DataServiceContext, сформированного программой Add Data Service Reference.

  • Неявное перечисление именованного объекта DataServiceQuery, который получен из контекста DataServiceContext, сформированного программой Add Data Service Reference.

  • Явный вызов метода Execute с объектом DataServiceQuery или метода BeginExecute для асинхронного выполнения.

Дополнительные сведения см. в разделе Запросы к службе данных (службы WCF Data Services).

Пример в этом разделе использует образец службы данных Northwind и автоматически сформированные клиентские классы службы данных. Эта служба и клиентские классы данных создаются после выполнения действий, описанных в разделе Краткое руководство по службам WCF Data Services.

Пример

Следующий пример показывает, как определить и выполнить запрос LINQ, возвращающий все сущности Customers в службе данных Northwind.

' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)

Try
    ' Define a LINQ query that returns all customers.
    Dim allCustomers = From cust In context.Customers _
                           Select cust

    ' Enumerate over the query obtained from the context.
    For Each customer As Customer In allCustomers
        Console.WriteLine("Customer Name: {0}", customer.CompanyName)
    Next
Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
            "An error occurred during query execution.", ex)
End Try
// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

try
{
    // Define a LINQ query that returns all customers.
    var allCustomers = from cust in context.Customers
                       select cust;

    // Enumerate over the query obtained from the context.
    foreach (Customer customer in allCustomers)
    {
        Console.WriteLine("Customer Name: {0}", customer.CompanyName);
    }
}
catch (DataServiceQueryException ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}

Следующий пример показывает, как использовать контекст, сформированный программой Add Data Service Reference, для неявного выполнения запроса, возвращающего все сущности Customers в службе данных Northwind. URI запрашиваемого набора сущностей Customers автоматически определяется контекстом. Запрос выполняется неявно при запуске перечисления.

' Create the DataServiceContext using the service URI.
Dim context = New NorthwindEntities(svcUri)

' Define a new query for Customers.
Dim query As DataServiceQuery(Of Customer) = context.Customers

Try
    ' Enumerate over the query result, which is executed implicitly.
    For Each customer As Customer In query
        Console.WriteLine("Customer Name: {0}", customer.CompanyName)
    Next
Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
            "An error occurred during query execution.", ex)
End Try
// Create the DataServiceContext using the service URI.
NorthwindEntities context = new NorthwindEntities(svcUri);

// Define a new query for Customers.
DataServiceQuery<Customer> query = context.Customers;

try
{
    // Enumerate over the query result, which is executed implicitly.
    foreach (Customer customer in query)
    {
        Console.WriteLine("Customer Name: {0}", customer.CompanyName);
    }
}
catch (DataServiceQueryException ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}

Следующий пример показывает, как использовать контекст DataServiceContext для явного выполнения запроса, который возвращает все сущности Customers в службе данных Northwind.

' Define a request URI that returns Customers.
Dim customersUri = New Uri(svcUri, "Northwind.svc/Customers")

' Create the DataServiceContext using the service URI.
Dim context = New DataServiceContext(svcUri)

Try
    ' Enumerate over the query result.
    For Each customer As Customer In context.Execute(Of Customer)(customersUri)
        Console.WriteLine("Customer Name: {0}", customer.CompanyName)
    Next

Catch ex As DataServiceQueryException
    Throw New ApplicationException( _
            "An error occurred during query execution.", ex)
End Try
// Define a request URI that returns Customers.
Uri customersUri = new Uri(svcUri, "Northwind.svc/Customers");

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

try
{
    // Enumerate over the query result.
    foreach (Customer customer in context.Execute<Customer>(customersUri))
    {
        Console.WriteLine("Customer Name: {0}", customer.CompanyName);
    }
}
catch (DataServiceQueryException ex)
{
    throw new ApplicationException(
        "An error occurred during query execution.", ex);
}

См. также

Задачи

Как добавить параметры запроса к запросу службы данных (службы WCF Data Services)