编写一个简单的OData客户端:如何查询服务

本文关键字:客户端 OData 查询服务 简单 一个 | 更新日期: 2023-09-27 18:18:59

我试图调整这个例子来创建一个简单的OData客户端。在此之前,我在Visual Studio中添加了一个服务引用到"http://services.odata.org/Northwind/Northwind.svc/"。

通过这一步,我得到了许多类,如"字母tical_list_of_product"。但是,如何获得按字母顺序排列的产品列表呢?

具体来说,在这个例子中,作者只是以:

开头
OdataClient.NorthwindOdataService.NorthwindEntities dc = 
    new OdataClient.NorthwindOdataService.NorthwindEntities(
        new Uri("http://services.odata.org/Northwind/Northwind.svc/")); 

但是他从哪里得到的OdataClient.NorthwindOdataService.NorthwindEntities类?

我是web服务和OData的新手,所以如果问题含糊不清,请原谅。

编写一个简单的OData客户端:如何查询服务

下面是一个示例,说明如何在将服务引用添加到项目中后使用它:

// Create a service context object
// "NorthwindEntities" is the name of the class in the generated service reference that derives DataServiceContext
// The URI in should be the same URI you used to add the service reference
var context = new NorthwindEntities(new Uri("http://services.odata.org/Northwind/Northwind.svc/"));
// As Alphabetical_list_of_products is an entity set, it can be directly called from the context
// Call Execute() finally to send the request to the OData service and materialize the response got to "products"
var products = context.Alphabetical_list_of_products.Execute();
// Iterate through all the products and print "ProductName", which is the name of a property on "Alphabetical_list_of_product" entity
foreach (var product in products)
{
    Console.WriteLine(product.ProductName);
}

由于您是OData新手,建议您从OData V4开始。Add Service Reference支持OData服务的客户端代理生成,直至OData V3。可以参考OASIS committee上的OData V4协议和Microsoft OData团队的博客。

如果您想要一个客户端来消费OData服务,一个不错的选择应该是OData代码生成器。您可以从阅读教程http://blogs.msdn.com/b/odatateam/archive/2014/03/12/how-to-use-odata-client-code-generator-to-generate-client-side-proxy-class.aspx开始。