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

时间:2014-08-21 23:58:02

标签: c# odata

我正在尝试调整this example来创建一个简单的OData客户端。在此之前,我在Visual Studio中将服务引用添加到“http://services.odata.org/Northwind/Northwind.svc/”。

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

具体来说,在示例中,作者只是以:

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

但他从哪里获得OdataClient.NorthwindOdataService.NorthwindEntities课程?

我是网络服务和OData的新手,如果问题含糊不清,请道歉。

2 个答案:

答案 0 :(得分:1)

以下是在将服务引用添加到项目后如何使用服务引用的示例:

// 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开始。添加服务引用支持OData服务的客户端代理生成,直到OData V3。可以参考OData V4 protocol on OASIS Comitteeblog of the OData team of Microsoft以获取详细信息。

答案 1 :(得分:0)

如果您希望客户端使用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

相关问题