can we convert Odata metadata to C# code (datacont

2019-09-17 06:17发布

问题:

there is a odata webservice, i can get metadata from

http://service-uri.com/$metadata

which contains definition of all its model object,

is there any tools that i can use, to convert that metadata xml to data contract class in C#?

回答1:

The WCF Data Services Client library can generate C# classes for you from the $metadata endpoint. These classes won't have the [DataContract] attribute, but you can use them with the rest of the client library to interact with the service.

To use this feature, download the latest "tools" installer for the client library, currently available here: http://www.microsoft.com/en-us/download/details.aspx?id=35840

(Note: If you want the latest stable bits of the client library, also run the following from the Package Manager Console window in Visual Studio: Install-Package Microsoft.Data.Services.Client)

Then, from within Visual Studio, you can right click on your project, and select "Add Service Reference". Here you can enter the $metadata URL of the service, and the corresponding classes will be generated, along with a DataServiceContext class you can use to interact with the service. For more info on querying the service, see this documentation: http://msdn.microsoft.com/en-us/library/dd673933.aspx

Or, if you want to generate the classes manually, you can use the DataSvcUtil.exe command line tool that comes with the tools installer. On my system, for example, that file is located at C:\Program Files (x86)\Microsoft WCF Data Services\Current\bin\tools\DataSvcUtil.exe

For instructions on how to use this tool, take a look at this page: http://msdn.microsoft.com/en-us/library/dd756369.aspx